我正在嘗試利用TeamTreehouse學習訂閱&這開始與編程邏輯和設計書來嘗試學習編程& python。請不要開槍殺死我我有重複結構的困難!無法在內部和外部for循環中傳遞變量值python 3.3
目標:我正試圖從外部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//////
......什麼?你期待什麼輸出,你會得到什麼? – jonrsharpe
我希望能夠得到在內部嵌套循環中收集的所有月份的累計總數。目前看來,外環的輸出來自第12個月的降雨輸入。 – L2g2h
當然好了,你每個月都把總數重置爲零。 – jonrsharpe