d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Basic Python Help Please > Paying Fg
Add Reply New Topic New Poll
Member
Posts: 9,711
Joined: Jun 13 2007
Gold: 1,734.25
Sep 28 2015 02:37pm
I am willing to pay some fg for help writing the following python program:

Distance Traveled

The distance a vehicle travels can be calculated as follows:
distance = speed X time

For example, if a train travels 40 miles per hour for three hours, the distance traveled is
120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hour)
and the number of hours it has traveled. It 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 desired
output:
What is the speed of the vehicle in mph? 40 [Enter]
How many hours has it traveled? 3 [Enter]
Hour Distance Traveled
1 40
2 80
3 120

What I got so far (I am a newb at this and cannot figure out how to get it to display right. I think the end is very wrong lol):

#This program gets the speed and hours driven of
#a vehicle then uses a loop and calculates the
#miles driven for each hour (3 hours)

#Initialize the accumulator
total=0

#Get the speed of the vehicle in miles per hour
speed=int(input("What was the speed of the vehicle (MPH)? "))

#Get the number of hours driven
hours_driven=int(input("How many hours did you drive? "))

#Calculate and display loop of distance traveled
distance=speed*hours_driven
for speed in range(1, hours_driven+1):
print("Hour", "distance", distance)

This post was edited by USArmy8786 on Sep 28 2015 02:43pm
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Sep 29 2015 10:47am
It's not bad, but your loop is incorrect. What you need to do is to dynamically compute the distance for each integer number of hours travelled.

Code
#This program gets the speed and hours driven of
#a vehicle then uses a loop and calculates the
#miles driven for each hour (3 hours)

#Get the speed of the vehicle in miles per hour
speed = int(input("What was the speed of the vehicle (MPH)?\n"))

#Get the number of hours driven
hours_driven = int(input("How many hours did you drive?\n"))

print("{:>5}{:>10}".format("Hour", "Distance"))

for hour in range(1, hours_driven+1):
print("{:>5}{:>10}".format(hour, hour * speed))


A live example is here: http://melpon.org/wandbox/permlink/AhESzVs2Y7WKodoT

This post was edited by KrzaQ2 on Sep 29 2015 10:47am
Member
Posts: 9,711
Joined: Jun 13 2007
Gold: 1,734.25
Sep 29 2015 01:01pm
Thank you very much man your explanation and code works perfect!! I sure appreciate the help!
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll