0
0
Pythonprogramming~15 mins

Try–except–finally behavior in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Try-except-finally 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 gracefully and always print a message at the end.
🎯 Goal: You will create a program that divides two numbers, handles division by zero using try and except, and always prints a final message using finally.
📋 What You'll Learn
Create two variables with exact values for dividend and divisor
Create a variable to store the result initialized to None
Use a try-except-finally block to perform division and handle ZeroDivisionError
Print the result or an error message
Always print a final message regardless of error
💡 Why This Matters
🌍 Real World
Handling errors like division by zero is common in programs that do calculations, such as calculators or financial apps.
💼 Career
Understanding try-except-finally is important for writing robust code that doesn't crash unexpectedly, a key skill for any programmer.
Progress0 / 4 steps
1
DATA SETUP: Create variables for dividend and divisor
Create two variables called dividend and divisor with values 10 and 0 respectively.
Python
Need a hint?

Use simple assignment like dividend = 10 and divisor = 0.

2
CONFIGURATION: Create a variable to store the result
Create a variable called result and set it to None.
Python
Need a hint?

Initialize result to None before the try block.

3
CORE LOGIC: Use try-except-finally to divide and handle errors
Write a try block that divides dividend by divisor and assigns it to result. Add an except ZeroDivisionError block that sets result to the string 'Cannot divide by zero'. Add a finally block that prints 'Execution completed'.
Python
Need a hint?

Use try, except ZeroDivisionError, and finally blocks exactly as described.

4
OUTPUT: Print the result
Write a print(result) statement to display the value of result.
Python
Need a hint?

Print the result after the try-except-finally block.