The divide by zero exception - Answers
Let's look at the options when handling a 'divide by zero' error.
Q1 - Q2 Get the following code working in Python:
1 num2=0 #Initiaise the variable
2 print("\nPlease enter the numbers ....\n")
3 while num2 == 0: #While the second number is zero do the following code
4 num1 = float(input('Enter the first number >>> ')) #Enter the first number
5 num2 = float(input('Enter the second number >>> ')) #Enter the second number
6 if num2 == 0: # If the second number still equals zero, display a message and re-enter the numbers.
7 print("You can't divide by zero. Please re-enter both numbers >>>\t")
8 print(num1,'/',num2,'=',num1/num2)
Q3. If you removed line 1, you would get an error saying num2 is not defined.
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")
The name of the exception we looked for in this program is ZeroDivisionError.