0

I want to convert a user's speed in km/h and display the time it takes. For example, if a user's input is 15 km/h then it should display 00.04.00 as it takes 4 minutes to run a kilometer with that pace.

I can't really figure out the math. The only thing I've found so far is (distance(1) / km/h(15))/60 gives the correct result of 4. However, if I were to calculate it at 9 km/h the result comes back as 6.66, and I know the time is supposed to be 00:06:40. I just don't know how to convert it correctly.

Sorry for being newbie.

Edit. I was able to solve this with some help. Here's my code

def inputNumber(message):
    while True:
        try:
            user_input = float(input(message))
        except ValueError:
            print("Please enter an appropriate value. For example, 15: ")
            continue
        else:
            return user_input

speed = inputNumber("Enter your running speed in km/h then this program will calculate minutes per kilometer: ")
while speed < 0:
    speed = inputNumber("Please reenter an appropriate value: ")
distance = 1  # 1 kilometer

seconds_speed = (distance / speed * 60)*60
minutes_speed = int((seconds_speed//60))
print("At that pace you'd run 1 kilometer in",
      minutes_speed,'minutes and',round(seconds_speed % 60),'seconds')
Moccar
  • 99
  • 2
  • 11
  • 66/100 = 2/3 and 40 minutes is 2/3 of an hour. – 001 Mar 13 '18 at 19:43
  • 1
    Time comes back as 6.66 - decimal system. Minutes have 60 seconds so this would be 6.66 * 60 seconds = 399,6s = 6 minues 39,6 seconds ... pretty close to your 6:40 considering you rounded your result to 2 digits to begin with... – Patrick Artner Mar 13 '18 at 19:43
  • Thanks! That makes sense! I think I'll be able to solve it now :-)! – Moccar Mar 13 '18 at 19:46

1 Answers1

2

You do not ask something Python specific, but since its tagged that way, I will give you a python related answer.

def calculate_duration(speed_in_kmh, distance_in_km=1):
    speed_in_ms = speed_in_kmh / 3.6
    distance_in_m = distance_in_km * 1000

    duration_in_s = distance_in_m / speed_in_ms

    return datetime.timedelta(seconds=duration_in_s)

>>> calculate_duration(15)
0:04:00
>>> calculate_duration(30)
0:02:00
>>> calculate_duration(60)
0:01:00
>>> calculate_duration(120)
0:00:30

This takes advantage of Pythons timedelta objects and using str() on those objects

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Hm, your right. I forgot to give it a default parameter; the question talks about 1km. – Ralf Mar 13 '18 at 20:04
  • Sorry. It's because I'm programming it in Python. Thanks for the answer. However, I was able to solve it myself. I didn't know about the timedelta as I'm still rather new to Python, but thanks for letting me know! – Moccar Mar 13 '18 at 20:23