Divide by 0 error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Divide by 0 error (/thread-4010.html) |
Divide by 0 error - kethyar - Jul-16-2017 I am having issues with my class assignment. My simple program is having a user input car speed, time traveled and tank capacity. However, when I go to calculate distance traveled (distance = input_speed * input_time) and then calculate MPG (mpg = distance / input_capacity), I am getting a divide by zero error. All of my previous inputs are listed as input_capacity = int(input("Input capacity: ")), but it is obviously not treating the number as an integer or a real number (in the case of using float for time). Can someone help me identify what I might be doing wrong or where I might need to tell the program to treat the input as a number? Sample input and my calculation formulas below: def capacity_prompt(): input_capacity = 0 input_capacity = int(input("Enter the number of gallons or liters used: ")) return input_capacity def calculate_distance(input_speed, input_time): result_distance = 0 result_distance = input_speed * input_time return result_distance def calculate_mpg(result_distance, input_capacity): result_mpg = 0 result_mpg = result_distance / input_capacity return result_mpg Bah, found my own error. I wasn't calling the functions at the end/beginning, I was calling the results. Called the correct variable and now it works fine. RE: Divide by 0 error - snippsat - Jul-16-2017 (Jul-16-2017, 04:10 PM)kethyar Wrote: I might need to tell the program to treat the input as a number?Yes,that's the first step. So if input is a or 1.0 ,get a error.>>> input_capacity = int(input("Enter the number of gallons or liters used: ")) Enter the number of gallons or liters used: a This ValueError can be catch and give a more useful message to user.def capacity_prompt(): while True: try: input_capacity = int(input("Enter the number of gallons or liters used: ")) return input_capacity except ValueError: print('Only number as input,try again') print(capacity_prompt())If you run it,you see that it will only return out integer. You use the same method with divide by zero error. >>> 7 / 0
|