For 循环到 运行 直到达到变量值

For loop to run until hitting variable value

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

我正在尝试查找有关如何制作 python 3.3.2 for 循环 运行 从值 0 到用户输入可变小时的值的教程。到目前为止,我只收到一个错误 运行ning 这段代码。我没有成功找到涵盖这种方法的教程。

下面的教程似乎涵盖了从零开始然后 运行 打印出 lists/dictionariies 的值 http://www.python-course.eu/python3_for_loop.php

与本教程相同 http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3/For_Loops

这让我开始思考,如果这不可能,我需要 research/learn 其他循环吗?

#//////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//////

不完全确定你正在尝试做什么,但使用 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()