Python:不能将关键字用作表达式

2024-04-19 07:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该设计一个程序,让用户在一个数组中输入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()

它一直在说我不能用关键字作为表达,我已经盯着它看了一个多小时了,现在我可能看了一些东西。在


Tags: nameinforindexlenifisrange
2条回答

Python通常会给您错误的行号,这对于解决这个问题非常重要。在

如果您在Python2中运行,那么您的第一个问题就在这里:

print ('Enter the amount of rain in',
months[index] = input(name_months[index] + ': '))

第一行没有右括号,第二行有太多右括号。在

当我把它改成

^{pr2}$

至少在Python 2.7(v3可能不同)中,它可以使用奇怪的列表输出格式:

Enter the amount of rain in Jan: 1
Enter the amount of rain in Feb: 2
Enter the amount of rain in Mar: 3
Enter the amount of rain in Apr: 4
Enter the amount of rain in May: 5
Enter the amount of rain in Jun: 6
Enter the amount of rain in Jul: 7
Enter the amount of rain in Aug: 8
Enter the amount of rain in Sep: 9
Enter the amount of rain in Oct: 0
Enter the amount of rain in Nov: 1
Enter the amount of rain in Dec: 2
('The total is', 48, 'mm.')
('The avarage rainfall is', 4.0, 'months')
('Lowest is', 0, 'in')
('Oct',)

('Highest is', 9, 'in')
('Sep',)

顺便说一句,如果Python已经提供了一个非常好的sum(),那么我就不会实现total()这样的函数。在

我无法重现您提到的错误,但您的代码似乎有点混乱,无法将其解释为注释。您似乎使用了Python2和Python3代码的混合体,但这不起作用—例如,您似乎希望:

print ('and',)

打印字符串'and',但禁止{}通常生成的新行。在Python 2中,它打印以下内容:

^{pr2}$

在Python 3中,这:

'and'

在这两种情况下,新线。在

发生这种情况是因为在Python2中逗号取消了换行符,但是括号不是语句的一部分,所以,您告诉它打印一个一项元组。在

在Python3中,这是一个普通的函数调用(因此括号的一部分),您可以告诉它在打印完成后将任意字符串放在末尾-它默认为换行符,但您可以将其更改为,例如,这样的空格:

print('and',end='')

你似乎还期望:

print

放一个空白行。在python2中,它会的。在Python3中,它不会做任何事情-您现在需要调用函数:

print()

使用输入的方式也会遇到问题:

months[index] = input(name_months[index] + ': ')

在Python2中,使用input函数被认为是个坏主意,通常建议使用raw_input。现在,input执行raw_input过去的工作,即返回一个字符串。其余代码假定每个months[index]都是一个数字,因此:

total += num

会做算术。当num(来自months)是一个字符串时,实际上会得到一个错误。这样做的方法是告诉Python在得到它之后将其转换为一个数字:

months[index] = int(input(name_months[index] + ': '))    

相关问题 更多 >