Adama Doumbia Adama Doumbia - 3 years ago 225
Python Question

Loop Table using distance = speed * time

The distance a vehicle travels can be calculated as follows:

distance = speed * time

Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output:

What is the speed of the vehicle in mph? 40

How many hours has it traveled? 3

Hour Distance Traveled




1 : 40

2 : 80

3 : 120

I've gotten everything done so far but can't manage to get the table to come out properly, as shown in the example table at the first hour (1) it should start at 40 but instead it starts at 120. Can someone help me fix the code? forgot to mention it should work for any value the user enters such as if someone was going 50 mph in 5 hours

g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))

if time <= 0 or speed <= 0:
print('Invalid Hours and mph must be greater than 0')
else:
for t in range(time):
distance = speed * time

print(t + 1,':', distance)
time = time * 2


g = 'n'
print('End')

Answer Source

Just change 2 things in your program. First, there's no need to double the time inside for loop, Second use variable t instead of time to calculate distance.

g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))

if time <= 0 or speed <= 0:
    print('Invalid Hours and mph must be greater than 0')
else:
    for t in range(time):
        distance = speed * (t+1)        // Use t+1 instead of time

        print(t + 1,':', distance)
        # time = time * 2              // No need to double the time


    g = 'n'
print('End')

Input: 
40
3

Output:
(1, ':', 40)
(2, ':', 80)
(3, ':', 120)
End
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download