![](/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.