0
0
Pythonprogramming~15 mins

Why exceptions occur in Python - See It in Action

Choose your learning style9 modes available
Why Exceptions Occur
📖 Scenario: Imagine you are writing a simple program that asks a user to enter two numbers and divides the first number by the second. Sometimes, things can go wrong, like if the user types a word instead of a number or tries to divide by zero. These problems cause exceptions in the program.
🎯 Goal: You will create a small program that shows why exceptions happen by trying to divide two numbers. You will see what causes errors and how Python tells you about them.
📋 What You'll Learn
Create two variables with exact names and values
Add a variable to hold the divisor
Write code that divides the numbers and can cause an exception
Print the result or the error message
💡 Why This Matters
🌍 Real World
Handling exceptions is important in real programs to avoid crashes and give users helpful messages.
💼 Career
Knowing why exceptions occur and how to handle them is a key skill for all programmers to write reliable software.
Progress0 / 4 steps
1
Create two variables with numbers
Create two variables called num1 and num2 with the exact values 10 and 0 respectively.
Python
Need a hint?

Use the equals sign = to assign values to variables.

2
Add a variable for the divisor
Create a variable called divisor and set it to the value of num2.
Python
Need a hint?

Assign the value of num2 to divisor using =.

3
Divide the numbers to cause an exception
Write a line that divides num1 by divisor and stores the result in a variable called result.
Python
Need a hint?

Use the division operator / to divide numbers.

4
Print the result or the error message
Use a try and except block to print result if division works, or print "Error: Division by zero is not allowed." if an exception occurs.
Python
Need a hint?

Put the division inside try, and catch ZeroDivisionError in except.