无法在内部和外部for循环python 3.3之间传递变量值

时间:2015-04-28 16:18:07

标签: for-loop global-variables pass-by-reference nested-loops python-3.3

我正在尝试使用TeamTreehouse学习订阅&这是从编程逻辑和设计书开始尝试学习编程&蟒蛇。请不要开枪杀我,我的重复结构有困难!

目标:我正在尝试从外部for循环中收集用户的输入。每个外循环迭代计算内循环将迭代12次;得到每个月的降雨量。然后外环将;显示整个时期(1或7年等)的月数,总降雨量和每月平均降雨量。

我正在阅读通过引用或值传递值来发现python具有可变和不可变的数据类型(int是一种不可变的数据类型)所以我不能简单地从我的理解中传递for循环之间的数据。那怎么能让它运作起来呢?我有一个向我建议的清单,虽然我不明白如何从列表中得到一个平均值,因为坦率地说它尚未在teamTreehouse或我的书的第4章中涵盖。 http://en.wikibooks.org/wiki/Python_Programming/Data_Types

错误:无法将数据从内部嵌套循环变量rainTotal传输到外部循环rainTotal。

CODE:

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

#//////VARIABLE DECLARATION//////
totalMonths=0
rainAverage=0
rainFall=0
rainTotal=0
#//////VARIABLE DECLARATION//////

#//////USER INPUT FUNCTION//////
def userInput():
    years=0
    months=12
#////don't understand how to function properly
#    monthly_rain = []
#////don't understand how to function properly
    print('This program will calculate the average rainfall over a period of years.')
    years=int(input("Please provide the number of years to calculate rainfall for."))
    for i in range(1, years + 1):
    #////////////////testing variable values correct////////////////
    #Placeholder
    #////////////////testing variable values correct////////////////
#//////USER INPUT FUNCTION//////
        for i in range(1, months + 1):
            rainTotal=int()
            monthlyRainFall=int(input("Please provide the rainfall in inches for month number " + str(i) + str(": ")))
#////don't understand how to function properly
#            monthly_rain.append(monthlyRainFall)
#////don't understand how to function properly
            rainTotal = rainTotal + monthlyRainFall
            rainAverage=rainTotal/months
            #//////testing variable <> value assignment/////
#///////// python code references/////////////
#            print('Calculating for a total number of', totalMonths, 'months.')
#            print('Months\t\t\t' + 'Average Rainfall')        
#            print(rain, '\t\t\t\t\t', i)
#/////////format references/////////////
    print("There was a total of ", (years*months), "months calculated.")
    print("The accumulative total of rainfall was ", rainTotal, " inches!")
    print("Average Rainfall per month:", rainTotal/(years*months))
# after the inner loop runs the following should display

#//////CALLING FUNCTION//////
userInput()
#//////CALLING FUNCTION//////

1 个答案:

答案 0 :(得分:1)

如上所述 - 请扩展您收到的错误。但是从查看代码开始,在进入内部循环之前尝试定义rainTotal。即:

for i in range(1, years + 1): rainTotal=int() #here for i in range(1, months + 1):