Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Divide by 0 error
#1
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.
Reply
#2
(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
Error:
Traceback (most recent call last):  File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'a' invalid literal for int() with base 10: '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
Error:
Traceback (most recent call last):  File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero division by zero
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Divide a Python Turtle program into subprograms TurtleOHG 5 3,327 Mar-21-2020, 02:07 PM
Last Post: buran
  divide a number iin two marciotos 2 1,896 Jan-20-2020, 12:25 PM
Last Post: marciotos
  Divide a vector Langosmon 1 2,665 May-13-2018, 09:09 AM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020