Solution: Safe Division
Explore how to safely perform division in Python by implementing input handling and try-except blocks. This lesson helps you understand error prevention and control flow to create programs that handle invalid input and avoid crashes.
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
tryblock 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 / bdivides 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
trypart and runs theexceptblock 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.")