Python if statement上的语法无效

2024-06-15 08:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始使用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")

“斯旺西”一词以红色突出显示


Tags: and代码ifprint语法错误红色beatdrew
3条回答

可能是因为所有If都需要小写if,所以出现了语法错误。同样,相等运算符是==不是=

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

Python区分大小写,因此If可能引发了无效语法。应该是if。在

你有两个问题:

  1. 您需要使用==进行比较测试,而不是=(这是用于变量赋值的)。在
  2. if必须是小写。记住Python是区分大小写的。在

但是,您应该在这里使用elif和{},因为这两个表达式不可能同时是{}:

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和{}会更好,原因有二:

  1. 代码清晰:很容易看出只有一个表达式将是True。在
  2. 代码效率:一旦表达式为True,求值将立即停止。但是,您当前的代码将始终计算所有三个表达式,即使第一个或第二个表达式是True。在

相关问题 更多 >