我遵循一门“网络编程”类(class),并且陷入了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

最佳答案

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")

关于python - 我的else语句始终是无效的语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32704491/

10-11 07:44
查看更多