簡體   English   中英

我的else語句始終是無效的語法

[英]My else statement is always an invalid syntax

我遵循一門“網絡編程”課程,並且陷入了Python的困境。 我的“ else”語句總是給出一個錯誤(語法無效)。 無論我嘗試使用哪種代碼(我從網絡使用的任何隨機代碼),我的else語句總是會遇到相同的錯誤。 這是一個非常簡單的代碼,給出了錯誤:

#!/usr/bin/python

test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else test1 == test2:
    print("is equal")

這是我在Terminal中得到的:

  File "varvergelijken3.py", line 10
    else test1 == test2:
             ^
SyntaxError: invalid syntax
test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

否則不附帶條件

或更理想地

test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

要了解更多信息,請參閱文檔

否則在python中沒有條件,您可以執行以下操作:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

或者,如果您想指定條件,請執行以下操作:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

else子句不帶參數-僅當不滿足if條件和所有elif條件時才執行。 您可以使用另一個elif條件:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

或者,由於如果test1都不小於test2 ,或者test2都不小於test1 ,則它們必須相等,因此簡單的else條件就足夠了:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

暫無
暫無

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

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