Handling errors prevents programs from crashing on unexpected input.
Basic try-except
try:
number = int(input("Enter a number: "))
print(10 / number)
except:
print("Invalid input or zero. Please try again.")
Specific errors
try:
age = int(input("Enter age: "))
print(100 / age)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Age cannot be zero.")
With else and finally
try:
num = int(input("Number: "))
except ValueError:
print("Not a number.")
else:
print(f"Success: {num * 2}")
finally:
print("Done.")
Simple examples
Safe calculator:
try:
a = float(input("First: "))
b = float(input("Second: "))
print(a / b)
except ValueError:
print("Enter numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Read number safely:
try:
value = int("hello")
except ValueError:
print("Conversion failed.")
Quick summary
- Put risky code in
try. - Catch errors in
except. - Use specific error types.
-
elseruns on success,finallyalways runs.
Practice adding try-except to input code. It makes programs more user-friendly in Python programs.
Top comments (0)