我应该设计一个程序,让用户在一个数组中输入12个月的总降雨量。程序应计算并显示一年的总降雨量、月平均降雨量以及最高和最低的月份。在
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 ('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, 'months')
m_copy = months[0:]
months.sort()
lowest = months[0]
print ('Lowest is', lowest, 'in',)
lows = []
for i in range (12):
if m_copy[i] == lowest:
lows.append( name_months[i] )
for i in range (len(lows)):
print (lows[i],)
if i < len(lows)-1: print ('and',)
print
highest = months[11]
print ('Highest is', highest, 'in',)
highs = []
for i in range (12):
if m_copy[i] == highest:
highs.append( name_months[i] )
for i in range (len(highs)):
print (highs[i],)
if i < len(highs)-1: print ('and',)
print
main()
它一直在说我不能用关键字作为表达,我已经盯着它看了一个多小时了,现在我可能看了一些东西。在
Python通常会给您错误的行号,这对于解决这个问题非常重要。在
如果您在Python2中运行,那么您的第一个问题就在这里:
第一行没有右括号,第二行有太多右括号。在
当我把它改成
^{pr2}$至少在Python 2.7(v3可能不同)中,它可以使用奇怪的列表输出格式:
顺便说一句,如果Python已经提供了一个非常好的
sum()
,那么我就不会实现total()
这样的函数。在我无法重现您提到的错误,但您的代码似乎有点混乱,无法将其解释为注释。您似乎使用了Python2和Python3代码的混合体,但这不起作用—例如,您似乎希望:
打印字符串}通常生成的新行。在Python 2中,它打印以下内容:
^{pr2}$'and'
,但禁止{在Python 3中,这:
在这两种情况下,和新线。在
发生这种情况是因为在Python2中逗号取消了换行符,但是括号不是语句的一部分,所以,您告诉它打印一个一项元组。在
在Python3中,这是一个普通的函数调用(因此括号是的一部分),您可以告诉它在打印完成后将任意字符串放在末尾-它默认为换行符,但您可以将其更改为,例如,这样的空格:
print('and',end='')
你似乎还期望:
放一个空白行。在python2中,它会的。在Python3中,它不会做任何事情-您现在需要调用函数:
使用输入的方式也会遇到问题:
在Python2中,使用
input
函数被认为是个坏主意,通常建议使用raw_input
。现在,input
执行raw_input
过去的工作,即返回一个字符串。其余代码假定每个months[index]
都是一个数字,因此:会做算术。当
num
(来自months
)是一个字符串时,实际上会得到一个错误。这样做的方法是告诉Python在得到它之后将其转换为一个数字:相关问题 更多 >
编程相关推荐