【发布时间】:2015-04-28 16:18:06
【问题描述】:
我正在尝试使用 TeamTreehouse 学习订阅和这本从编程逻辑和设计开始的书来尝试学习编程和 python。请不要开枪打死我,我在重复结构方面遇到困难!
目标:我试图在外部 for 循环中收集用户的输入。每次外循环迭代计算,内循环将迭代12次;获取每个月的降雨量。然后外循环;显示整个时间段(1 年或 7 年等)的月数、总降雨量和每月平均降雨量。
我正在阅读通过引用或按值传递值的内容,以发现 python 具有可变和不可变数据类型(其中 int 是不可变数据类型),因此根据我的理解,我不能简单地在 for 循环之间传递数据。那我该如何让它发挥作用呢?我有一个建议给我的列表,虽然我不明白如何从列表中获取平均值,因为坦率地说,到目前为止,teamTreehouse 或我的书的第 4 章都没有涵盖它。 http://en.wikibooks.org/wiki/Python_Programming/Data_Types
错误:无法获取从内部嵌套循环变量rainTotal 传输到外部循环rainTotal 的数据。
代码:
#//////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//////
【问题讨论】:
-
...什么?!你期待什么输出,而你得到了什么?
-
我希望能够获得内部嵌套循环中收集的所有月份的累计总数。目前外循环中的输出似乎来自第 12 个月的降雨输入。
-
当然是这样,您将每个月的总数重置为零。
-
标签: for-loop global-variables pass-by-reference nested-loops python-3.3