211k views
13 votes
This program asks the user for two numbers - a numerator and a denominator - and determines whether or not they divide evenly. However, this program has a problem: if the user enters zero as the denominator, the program will crash!

Right now, the program looks like this:

numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter denominator: "))

# If denominator is 0, this will result in a division-
# by-zero error!
if (numerator / denominator * denominator) == numerator:
print("Divides evenly!")
else:
print("Doesn't divide evenly.")

1 Answer

9 votes

Answer:

You can add a validation routine. This will check whether or not the user has entered the correct value.

Step-by-step explanation:

Step 1: Look at the Python program properly :

numerator = int(input("Enter a numerator: "))

denominator = int(input("Enter denominator: "))

if ((numerator / denominator) * denominator) == numerator:

print("Divides evenly!")

else:

print("Doesn't divide evenly.")

Step 2: Add the validation routine:

if denominator == 0:

print("Error - Invalid Denominator")

else:

...

Step 3: Add the routine into the program:

numerator = int(input("Enter a numerator: "))

denominator = int(input("Enter denominator: "))

if denominator == 0:

print("Error - Invalid Denominator")

else:

if ((numerator / denominator) * denominator) == numerator:

print("Divides evenly!")

else:

print("Doesn't divide evenly.")

- Educator

User Shu
by
4.3k points