![](/img/trans.png)
[英]Python syntax error: can't assign to operator in module but works in interpreter
[英]Python : 'Can't assign to operator' Syntax error
我正在尝试编写一个程序,其中将测试分数收集在列表中,然后输出某些因素,例如最高分。 但是,当我尝试分配 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]`
您不能使用and
来分配两个变量。 Python 将您的作业解析为:
intH1 = (score1_list[intCount] and strHN1) = name_list[intCount]
试图将name_list[intCount]
表达式的结果分配给intH1
和score1_list[intCount] and strHN1
。 and
是一个运算符,只能在表达式中使用,但赋值是一个语句。 语句可以包含表达式,表达式不能包含语句。
这就是为什么定义的赋值语法使用语法实体 *expression_list and
yield_expression , two expression forms you can use, only in the part to the right of the
=` 等号, 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]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.