Try-except-else behavior
📖 Scenario: Imagine you are writing a small program that divides numbers. Sometimes the user might enter zero as the divisor, which causes an error. You want to handle this error nicely and also do something special when there is no error.
🎯 Goal: You will create a program that tries to divide two numbers, catches division errors, and uses else to print a success message only when no error happens.
📋 What You'll Learn
Create two variables
numerator and denominator with exact valuesCreate a variable
result and set it to NoneUse a
try block to divide numerator by denominator and store in resultUse an
except ZeroDivisionError block to set result to the string 'Cannot divide by zero'Use an
else block to print 'Division successful'Finally, print the value of
result💡 Why This Matters
🌍 Real World
Handling errors like division by zero is common in calculators, data processing, and user input validation.
💼 Career
Understanding try-except-else helps you write robust code that doesn't crash and gives clear feedback, a key skill for any programmer.
Progress0 / 4 steps