【问题标题】:Python : 'Can't assign to operator' Syntax errorPython:“无法分配给运算符”语法错误
【发布时间】:2015-10-10 13:14:34
【问题描述】:

我正在尝试编写一个程序,将测试分数收集在列表中,然后输出某些因素,例如最高分数。但是,当我尝试分配 intH1(测试 1 的最高结果)时,出现上述错误。该行是intH1 = score1_list[intCount] and strHN1 = name_list[intCount]

if score1_list[intCount] > intH1:
     intH1 = score1_list[intCount] and strHN1 = name_list[intCount]
if score2_list[intCount] > intH2:
     intH2 = score2_list[intCount] and strHN2 = name_list[intCount]
if score3_list[intCount] > intH3:
     intH3 = score3_list[intCount] and strHN3 = name_list[intCount]
if total_list[intCount] > intHT:
     intHT = total_list[intCount] and strHNT = name_list[intCount]`

【问题讨论】:

  • 您希望intH1 = score1_list[intCount] and strHN1 = name_list[intCount] 实现什么目标?这不是有效的 Python。
  • 如果intH1 小于score1_list[intCount],我试图将intH1 更改为score1_list[intCount],并将strHN1(学生姓名)更改为name_list[intCount],以便他们可以一起输出说“测试 1 的最高分是 ... 由 ...”。我为我糟糕的代码道歉,我只学了几个星期的 Python。

标签: python arrays syntax-error assign


【解决方案1】:

您不能使用and 来分配两个变量。 Python 将您的作业解析为:

intH1 = (score1_list[intCount] and strHN1) = name_list[intCount]

试图将name_list[intCount] 表达式的结果分配给intH1score1_list[intCount] and strHN1and 是运算符,只能在表达式中使用,但赋值是语句。语句可以包含表达式,表达式不能包含语句。

这就是defined grammar for assignments 使用语法实体 *expression_listandyield_expression, two expression forms you can use, only in the part to the right of the=` 等号的原因:

assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)

target_list 定义不允许使用任意表达式。

使用单独的行进行赋值:

intH1 = score1_list[intCount]
strHN1 = name_list[intCount]

或使用元组赋值:

intH1, strHN1 = score1_list[intCount], name_list[intCount]

【讨论】:

  • 谢谢你已经解决了。
【解决方案2】:

if 的每个分支都执行两项任务。它们之间不需要and,只需将它们分成两个语句:

if score1_list[intCount] > intH1:
    intH1 = score1_list[intCount]
    strHN1 = name_list[intCount]
if score2_list[intCount] > intH2:
    intH2 = score2_list[intCount]
    strHN2 = name_list[intCount]
if score3_list[intCount] > intH3:
    intH3 = score3_list[intCount]
    strHN3 = name_list[intCount]
if total_list[intCount] > intHT:
    intHT = total_list[intCount]
    strHNT = name_list[intCount]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 2021-10-03
    • 2021-04-06
    • 2015-04-29
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多