Python Forum

Full Version: Converter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wanted to make converter from Miles to Km and have estimated driving time in my program . The problem is i cant not print exactly driving time .
if i use //, instead of /. This forces Python to do an integer division (i.e. ignore decimal points) since we ignore decimal points if input number less than 57 estimated time will be 0

for example if i enter input miles 280 result is "Estimated driving time 4.977777777777778 hours" i wanted to make something like 4hours 59mins in this case
distanceMiles = input("Miles ? ")
distanceKM = int(distanceMiles) * 1.6
meters = int(distanceKM) * 1000
centimeter = int(meters) *100

drive = distanceKM/90  #speed per hour

print(" in kilometers is", distanceKM, "km")
print(meters, "meters")
print(centimeter, "cm")
print("Estimated driving time",drive, "hours")
Wall
If you want just hours, you can ask python to limit the number of decimals.
>>> hours = 22/7
>>> print(f"{hours:.2f} hours to drive")
3.14 hours to drive
It would also not be too hard to convert that manually to hours:minutes (remove integer hours, multiply fractional part by 60).

>>> h,m = divmod(hours*60, 60)
>>> m = round(m)
>>> print(f"The drive should take {h:.0f}:{m:02d}")
The drive should take 3:09
datetime/timedelta can do that for you as well, but I find it annoying that the formatting options for timedelta are so limited.

>>> from datetime import timedelta
>>> str(timedelta(hours=hours))
'3:08:34.285714'
You'd have to split out the string as needed, or maybe pull total_seconds() from it and trim to an int to remove the sub-second part....
2nd option worked well, first option code only gives result 3.14 i think i made something wrong tnx a lot for your answer