任务是编写一个程序,要求用户输入12个月中每个月的总降雨量。输入将存储在列表中。然后,该计划应计算并显示该年度的总降雨量,月平均降雨量以及最高和最低量的月份。
我应该通过使用循环循环20次并在输入后将每个分数附加到列表来执行此操作。请记住我是初学者。到目前为止,这是我的代码:
def main():
months = [0] * 12
name_months = ['Jan','Feb','Mar','Apr','May','Jun', \
'Jul','Aug','Sep','Oct','Nov','Dec']
def total(months):
total = 0
for num in months:
total += num
return total
for index in range(12):
print('Please enter the amount of rain in')
months[index] = input(name_months[index] + ': ')
print('The total is'), total(months),'mm.'
avarage = total(months) / 12.0
print('The avarage rainfall is'), avarage,'mm.'
main()
答案 0 :(得分:2)
这必须是Python 3.您必须将用户输入转换为数字而不是字符串:
# Sets months[index] to a string
months[index] = input(name_months[index] + ': ')
应该是:
# Sets months[index] to a (floating-point) number
months[index] = float(input(name_months[index] + ': '))
答案 1 :(得分:1)
然后老师要求使用一个循环20次的循环,并在输入后将每个分数附加到列表中。
除非你应该使用一个非常奇怪的日历,否则20必须是一个错字。 :)
错误原因:
您正在将total
初始化为0
,但之后尝试向其添加字符串,因为input
将返回一个字符串。您必须首先将输入转换为整数(或浮点)值。
清理程序的建议:
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
am = [int(input('input rainfall for {}: '.format(m))) for m in months]
comb = list(zip(months,am))
total = sum(am)
avg = total/12
least = min(comb, key=lambda x: x[1])
most = max(comb, key=lambda x: x[1])
print('month\tamount')
for mon, amount in comb:
print('{0}\t{1}'.format(mon, amount))
print('total: {}'.format(total))
print('average: {}'.format(avg))
print('least rain in: {0} ({1})'.format(least[0], least[1]))
print('most rain in: {0} ({1})'.format(most[0], most[1]))
示例运行:
input rainfall for Jan: 1
input rainfall for Feb: 2
input rainfall for Mar: 3
input rainfall for Apr: 4
input rainfall for May: 5
input rainfall for Jun: 6
input rainfall for Jul: 7
input rainfall for Aug: 8
input rainfall for Sep: 9
input rainfall for Oct: 10
input rainfall for Nov: 11
input rainfall for Dec: 12
month amount
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
total: 78
average: 6.5
least rain in: Jan (1)
most rain in: Dec (12)
答案 2 :(得分:-2)
使用+
运算符无法将String与Integer连接起来。您必须使用str(int)
将整数转换为字符串。
>>> 10 + '10'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'