0
0
Pythonprogramming~15 mins

Multiple exception handling in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Multiple exception handling
📖 Scenario: You are writing a simple calculator program that takes two numbers and divides them. Sometimes, users might enter invalid input or try to divide by zero. You want to handle these errors gracefully.
🎯 Goal: Build a program that asks for two numbers, divides them, and uses multiple exception handling to catch ValueError and ZeroDivisionError.
📋 What You'll Learn
Create two variables num1 and num2 to store user input
Create a variable to store the division result
Use a try block to convert inputs to integers and perform the division
Use multiple except blocks to catch ValueError and ZeroDivisionError
Print the result if no error occurs
💡 Why This Matters
🌍 Real World
Handling errors is important in programs that take user input or perform calculations to avoid crashes and provide clear feedback.
💼 Career
Knowing how to manage multiple exceptions is a key skill for writing robust and user-friendly software.
Progress0 / 4 steps
1
Create variables for user input
Create two variables called num1 and num2. Assign input("Enter first number: ") to num1 and input("Enter second number: ") to num2.
Python
Need a hint?

Use input() to get user input as strings.

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

Initialize result to None before using it.

3
Use try and multiple except blocks
Write a try block that converts num1 and num2 to integers using int(), divides them, and assigns it to result. Add two except blocks: one for ValueError that prints "Invalid input! Please enter numbers." and one for ZeroDivisionError that prints "Cannot divide by zero.".
Python
Need a hint?

Put the integer conversions and division inside try. Use separate except blocks for each error type.

4
Print the result
Write a print statement that prints "Result: " followed by the value of result only if result is not None.
Python
Need a hint?

Use if result is not None: before printing.