AI Features

Solution: Safe Division

We'll cover the following...

This program asks the user to enter two numbers and then divides them. It also includes error handling using a try-except block to prevent the program from crashing if something goes wrong.

  • The try block contains code that might cause an error.

  • Inside it:

    • input() asks the user to type two numbers.

    • int() converts those inputs from text to integers.

    • result = a / b divides the first number by the second.

    • print() shows the result.

  • If any problem occurs (for example, typing text instead of a number or dividing by zero), Python skips the try part and runs the except block instead, showing:

    • Oops! Something went wrong.

try:
    a = int(input("Enter a number: "))
    b = int(input("Enter another number: "))
    result = a / b
    print("Result:", result)
except:
    print("Oops! Something went wrong.")
Safely dividing two numbers and handling division by zero and invalid input