循环运行直到达到变量值

时间:2015-04-25 20:38:47

标签: python loops for-loop python-3.3

我正在尝试在自我思考与我相关的项目和利用teamtreehouse之间学习Python,尽管它进展缓慢。

我正在尝试找到一个关于如何使用python 3.3.2进行循环运行的教程,从0开始直到用户输入变量小时的值。到目前为止,我只是在运行此代码时出错。我没有成功找到涵盖这种方法的教程。

下面的教程似乎涵盖了从什么时候开始,然后运行打印出列表/词典的值 http://www.python-course.eu/python3_for_loop.php

本教程也是如此 http://en.wikibooks.org/wiki/Non-Programmer“s_Tutorial_for_Python_3 / For_Loops

这让我想到如果不可能,而我需要研究/学习其他循环?

#//////MAIN PROGRAM START//////

#//////VARIABLE DECLARATION//////
speedMPH=0
timeTraveling=0
hours=1
distanceTraveled=0
#//////VARIABLE DECLARATION//////

#//////USER INPUT FUNCTION//////
def userInput():
    speedMPH=int(input("Please provide the speed the vehicle was going in MPH."))
    hours=int(input("Please provide the number of hours it has been traveling in hours."))
    #////////////////testing variable values correct////////////////
#    print(speedMPH)
#    print(hours)
#    print(distanceTraveled)
    #////////////////testing variable values correct////////////////
#//////USER INPUT FUNCTION//////
    print('Distance Traveled\t\t\t' + 'Hours')
    for i in range(1, hours + 1):
        distanceTraveled=0
        distanceTraveled = speedMPH * i
        print(distanceTraveled, '\t\t\t\t\t', i)
#//////CALLING FUNCTION//////
userInput()
#//////CALLING FUNCTION//////

1 个答案:

答案 0 :(得分:1)

不完全确定你要做的是什么,但是使用range并将代码保持为单个函数将更加接近:

def user_input():
    # keep track of running total 
    total_distance = 0
    # cast hours and mph to int 
    speed_mph = int(input("Please provide the speed the vehicle was going in MPH."))
    hours = int(input("Please provide the number of hours it has been traveling in hours."))
    # loop from 1 to hours + 1, ranges are not inclusive
    for i in range(1, hours + 1):
        distance_traveled = speed_mph * i
        total_distance += distance_traveled 
        print("Travelled {} miles after {} hour/s".format( distance_traveled,i))

    print("Total distance travelled {} miles after {} hour/s".format(total_distance,hours))
user_input()