0
我想彙總總降雨量以英寸顯示總數,但是當我運行代碼時,我得到一個TypeError說「'浮動'對象不可迭代」。任何想法我做錯了什麼?'float'對象不可迭代?
months = 12
def main():
rain = get_rain()
total = get_total(rain)
avg = total/len(rain)
low = min(rain)
high = max(rain)
print('The total rainfall in inches for the year is: ', format(total, ',.2f'))
print()
print('The average monthly rainfall this year was: ', format(avg, ',.2f'))
print()
print('The lowest rainfall in inches this year was: ', format(low, ',.2f'))
print()
print('The highest rainfall in inches this year was: ', format(high, ',.2f'))
print()
def get_rain():
rain_in = []
print('Enter the amount of rainfall in inches for each month of the year.')
print('------------------------------------------------------')
for index in range(months):
print('Enter the total rainfall in inches for month #', index + 1, ': ', sep='', end='')
rain_inches = float(input())
rain_in.append(rain_inches)
return rain_inches
def get_total(rain_in_list):
total = 0.0
for num in rain_in_list:
total += num
return total
main()
回溯:
Traceback (most recent call last):
File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 50, in <module>
main()
File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 9, in main
total = get_total(rain)
File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 45, in get_total
for num in rain_in_list:
TypeError: 'float' object is not iterable
甚至有點在正確的方向,將有助於推的。我覺得我正處於解決這個問題的邊緣。
請張貼完整回溯 – TerryA
'輸入()'接受一個提示字符串,所以最好使用'輸入(「輸入降雨量...「)'。 –
與您的例外無關:您可以使用'str.format'方法而不是內置'format'函數簡化一些打印調用。例如,'print('年份的總降雨量是英寸:{.2f}'。format(total))''。對於你的輸入提示,你可以在'input'調用中進行這種格式化(它將被打印在請求輸入的行的開始處):'input('輸入月份的總降雨量,以英寸爲單位#{} :'.format(index + 1))' – Blckknght