0
0
Pythonprogramming~20 mins

Common exception types in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Common exception types
📖 Scenario: Imagine you are writing a small program that asks a user to enter two numbers and divides the first number by the second. Sometimes, users might enter wrong data or cause errors like dividing by zero. We want to learn how to handle these common mistakes using exceptions.
🎯 Goal: You will create a program that safely divides two numbers entered by the user. You will handle common errors like entering text instead of numbers and dividing by zero, so the program does not crash and shows friendly messages.
📋 What You'll Learn
Create variables num1_str and num2_str to store two inputs entered by the user
Create a variable to store the result of division
Use try-except blocks to catch ValueError and ZeroDivisionError
Print the result if division is successful
Print clear error messages if exceptions occur
💡 Why This Matters
🌍 Real World
Handling errors like invalid input or division by zero is common in programs that take user input or do calculations. This makes programs more user-friendly and reliable.
💼 Career
Knowing how to catch and handle exceptions is a basic skill for software developers, especially when building applications that interact with users or external data.
Progress0 / 4 steps
1
DATA SETUP: Get two inputs from the user
Create two variables called num1_str and num2_str. Use input() to get values from the user.
Python
Need a hint?

Use input() to store the user's input as strings in num1_str and num2_str.

2
CONFIGURATION: Prepare a variable for the division result
Create a variable called result and set it to None. This will hold the division result later.
Python
Need a hint?

Set result to None before doing the division.

3
CORE LOGIC: Use try-except to divide and catch errors
Use a try block to convert num1_str and num2_str to integers num1 and num2, divide num1 by num2 and store the result in result. Add except ValueError to catch invalid number inputs and except ZeroDivisionError to catch division by zero. Print a friendly message inside each except block.
Python
Need a hint?

Put the int() conversions and division inside try. Catch ValueError and ZeroDivisionError with except blocks.

4
OUTPUT: Print the division result if successful
After the try-except blocks, write a print() statement that shows result only if it is not None. Use an if statement to check this.
Python
Need a hint?

Check if result is not None before printing it.