Home > Enterprise >  How can i display this for loop, correctly?
How can i display this for loop, correctly?

Time:05-26

okay so i have project i am working on, its very basic, but i couldnt figure it out after about 2 hours so i am coming here to try and get some help, (for what it is worth, i do not consider myself a programmer)

Here is the code

speed = int(input('Please enter speed in MPH '))
hours = int(input('Please enter the time traveled, in hours '))

for distance in range(hours):
print('Hour', hours, 'Distance Traveled', hours * speed)

for distance2 in range(hours):

    print(hours, speed)

So with that said, i need to be able to print it, similar to something like this

Hour    Distance Traveled
1       40
2       80
3       120

Mine displays like this

Please enter speed in MPH 70
Please enter the time traveled, in hours 3
Hour 3 Distance Traveled 210
3 70
3 70
3 70
Hour 3 Distance Traveled 210
3 70
3 70
3 70
Hour 3 Distance Traveled 210
3 70
3 70
3 70

If you can provide a hint to the next direction, that would be swell

CodePudding user response:

I don't see why you need to loop over it twice. You should instead print the header, then loop over the hours, calculating the distance at each hour. Also, I think you want to use \t to print a tab character. I found this code works:

speed = int(input('Please enter speed in MPH '))
hours = int(input('Please enter the time traveled, in hours '))

print("Hour\tDistance Traveled")

for hour in range(hours):
    print("{}\t{}".format(hour 1, (hour 1)*speed))

I also added 1 to each hour, because the range() function starts at 0, not 1

CodePudding user response:

There is no need for another loop. It's okay to make mistakes when you first start programming in any language.

speed = int(input("Please enter speed in MPH: "))
hours = int(input("Please enter the time traveled, in hours: "))

print("\nHour\tDistance Traveled")
for hour in range(hours):
    print("{}\t{}".format(hour 1, (hour 1)*speed))
  • Related