[英]Invalid Syntax on Python if statement
我最近開始使用Python,當我收到一個無效的語法錯誤時,我正在鍵入一個簡單的代碼,有人知道我出了錯嗎?
Swansea= 2
Liverpool= 2
If Swansea < Liverpool:
print("Swansea beat Liverpool")
If Swansea > Liverpool:
print("Liverpool beat Swansea")
If Swansea = Liverpool:
print("Swansea and Liverpool drew")
“斯旺西”一詞以紅色突出顯示
您有兩個問題:
==
用於比較測試,而不是=
(用於變量分配)。 if
需要小寫。 請記住,Python區分大小寫。 但是,您應該在這里使用elif
, else
在這里使用,因為其中兩個表達式不可能同時為True
:
Swansea=2
Liverpool=2
if Swansea < Liverpool:
print("Swansea beat Liverpool")
elif Swansea > Liverpool:
print("Liverpool beat Swansea")
else:
print("Swansea and Liverpool drew")
盡管使用三個單獨的if
不會產生錯誤,但是使用elif
和else
會更好,原因有兩個:
True
。 True
評估將立即停止。 但是,即使第一個或第二個為True
,您當前的代碼仍將始終對所有三個表達式求值。 您可能會因為所有If
需要將小寫if
的語法錯誤。 而且相等運算符是==
不是=
if Swansea == Liverpool:
print("Swansea and Liverpool drew")
Python區分大小寫,因此可能是If
引發了無效的語法。 應該是if
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.