Back

The divide by zero exception

Q1. Get the following code working in Python:

1    num2=0
2    print("\nPlease enter the numbers ....\n")
3    while num2 == 0:
4        num1 = float(input('Enter the first number >>> '))
5        num2 = float(input('Enter the second number >>> '))
6        if num2 == 0:
7             print("You can't divide by zero. Please re-enter both numbers >>>\t")
8    print(num1,'/',num2,'=',num1/num2)

Q2. Explain what the program does.
Q3. What would happen if you removed line 1?
Q4. Now get the following code working:

#Divide by zero example using an exception

num2=0
print("\nPlease enter the numbers ....\n")
while num2 == 0:
    try:
        num1 = float(input('Enter the first number >>> '))
        num2 = float(input('Enter the second number >>> '))
        print(num1,'/',num2,'=',num1/num2)
    except ZeroDivisionError:
        print("You can't divide by zero. Please re-enter the numbers ....\n")

What is the name of the exception we used in this program?

Back