How to calculate time if we have the distance and speed (kilometers per hour) in Python

1 Answer

0 votes
import math

# Initialize distance and speed
distance = 30  # (in km)
speed = 90     # (in km/h)

# Check to avoid division by zero
if speed <= 0:
    print("Speed must be greater than zero.")
    sys.exit(1)

# Calculate time
tm = distance / speed

print(f"Time required: {tm:.2f} hours")

# Optional: convert to hours and minutes
hours = math.floor(tm)
minutes = round((tm - hours) * 60)

print(f"Which is approximately {hours} hours and {minutes} minutes.")



'''
run:

Time required: 0.33 hours
Which is approximately 0 hours and 20 minutes.

'''

 



answered Dec 6, 2025 by avibootz

Related questions

...