CodeSolved

A comprehensive source of programming questions and exercises

Calculate speed

Practice Easy 840/ Download 508 Views

Write a program that takes the distance and the time to print speed in the output

Speed ​​= to move / time

12 Answers

# Calculate speed
D = int(input("Distance traveled: "))
T = int(input("Time: "))
if D <= 0 or T <= 0:
print("Error!")
else:
print("Speed:",D/T)
# Dictionary of distance units with their names
Distance_unit = {
1: "miles",
2: "kilometers",
3: "nautical miles",
4: "yards",
5: "feet",
6: "inches",
7: "millimeters",
8: "centimeters",
9: "meters"
}
# Dictionary of time units with their names
Time_unit = {
1: "hours",
2: "minutes",
3: "seconds"
}
# Input validation function
def get_valid_input(prompt, valid_range):
while True:
try:
value = int(input(prompt))
if value in valid_range:
return value
print(f"Please enter a number between {min(valid_range)} and {max(valid_range)}")
except ValueError:
print("Please enter a valid number")
# Get distance unit input with validation
Distance_unit_input = get_valid_input(
"Enter the unit of distance you want to convert from\n"
"1(miles) 2(kilometers) 3(nautical miles) 4(yards)\n"
"5(feet) 6(inches) 7(millimeters) 8(centimeters) 9(meters): ",
Distance_unit.keys()
)
# Get time unit input with validation
Time_unit_input = get_valid_input(
"Enter the unit of time you want to convert from:\n"
"1(hours) 2(minutes) 3(seconds): ",
Time_unit.keys()
)
# Get distance and time values with validation
while True:
try:
Distance_traveled = float(input(f"Enter the distance traveled in {Distance_unit[Distance_unit_input]}: "))
if Distance_traveled >= 0:
break
print("Distance must be non-negative")
except ValueError:
print("Please enter a valid number")
while True:
try:
Time_traveled = float(input(f"Enter the time traveled in {Time_unit[Time_unit_input]}: "))
if Time_traveled > 0:
break
print("Time must be greater than zero")
except ValueError:
print("Please enter a valid number")
# Calculate speed
Speed = Distance_traveled / Time_traveled
# Print result with proper formatting
print(f"The speed is {Speed:.2f} {Distance_unit[Distance_unit_input]} per {Time_unit[Time_unit_input]}")
Soroush Download Python
<< Previous page 1 2 Next Page >>

Submit answer

Submitting answers is currently unavailable.

Related content

Detection using AI
×
×