Skip to main content
 首页 » 编程设计

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

2025年05月04日8cyq1162

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

我正在尝试查找有关如何使 python 3.3.2 for 循环从值 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////// 

请您参考如下方法:

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