Write a program that asks for two numbers to divide, but use try/except to handle non-numbers and division by zero. (Concepts: try/except, exceptions, input validation)
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Please enter valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")Day 19: Make code robust with error handling! try: block runs risky code: Inputs to floats (crashes on non-numbers), divide, print. If error, jumps to except. except ValueError: catches input conversion fails (e.g., "abc"). except ZeroDivisionError: for /0.
Run: Valid 10/2=5.0; "abc" → ValueError message; 5/0 → ZeroDivision. Graceful—no crash! In 10-15 min, add a general except Exception: for others. Try/except prevents bugs; always validate inputs. Ties to Day 2 math safely!
Key Concepts:
- try/except: try: tests code; except ExceptionType: catches and handles specific errors without crashing.
- Exceptions: Built-in errors like ValueError (bad conversion) or ZeroDivisionError (math issue).
- Input Validation: Checking user input before use to avoid errors (e.g., converting safely).
