Search⌘ K
AI Features

Solution: Safe Division

Understand how to write a Python program that divides two user-provided numbers safely. Learn to use try-except blocks to handle errors such as invalid entries or division by zero, ensuring your program runs smoothly without crashing.

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