簡體   English   中英

Python if語句上的語法無效

[英]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")

“斯旺西”一詞以紅色突出顯示

您有兩個問題:

  1. 您需要將==用於比較測試,而不是= (用於變量分配)。
  2. if需要小寫。 請記住,Python區分大小寫。

但是,您應該在這里使用elifelse在這里使用,因為其中兩個表達式不可能同時為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不會產生錯誤,但是使用elifelse會更好,原因有兩個:

  1. 代碼清晰:很容易看到只有一個表達式為True
  2. 代碼效率:表達式為True評估將立即停止。 但是,即使第一個或第二個為True ,您當前的代碼仍將始終對所有三個表達式求值。

您可能會因為所有If需要將小寫if的語法錯誤。 而且相等運算符是==不是=

if Swansea == Liverpool: 
     print("Swansea and Liverpool drew")

Python區分大小寫,因此可能是If引發了無效的語法。 應該是if

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM