62.5k views
5 votes
Write a program that asks the user the speed of a vehicle (in miles per hour) and

how many hours it has traveled. The program will display the total distance traveled
at the end of each hour of the period. (Python)

Write a program that asks the user the speed of a vehicle (in miles per hour) and-example-1

1 Answer

4 votes

Answer:

Here's a Python program that calculates and displays the total distance traveled by a vehicle over a period of time, using functions to validate the user's input:

def get_integer_data(prompt):

while True:

try:

value = int(input(prompt))

if value <= 0:

print("Please enter a positive integer.")

else:

return value

except ValueError:

print("Please enter a valid integer.")

def main():

speed = get_integer_data("What is the speed of the vehicle in mph: ")

hours = get_integer_data("How many hours has it traveled? ")

print("\\Distance Traveled Summary")

print("Hour\tDistance Traveled (miles)")

for hour in range(1, hours+1):

distance = speed * hour

print(f"{hour}\t{distance}")

main()

Step-by-step explanation:

Here's how the program works:

First, a function named get_integer_data is defined that takes a prompt as an argument and asks the user to enter a positive integer value. If the user enters a non-positive or invalid value, the function will prompt the user again until a valid input is given.

Then, the main function is defined. It calls the get_integer_data function twice to get the speed and hours traveled from the user.

After that, the program displays a summary of the distance traveled at each hour of the period. A for loop is used to iterate over each hour from 1 to hours. Inside the loop, the distance traveled is calculated by multiplying the speed by the hour. The f-string syntax is used to format and print the hour and distance values in a table.

Note that the program assumes that the speed is constant over the entire period. If this is not the case, the program would need to be modified to take this into account.

User Adeel Ahmed Baloch
by
8.0k points