【问题标题】:Python elif else syntaxError [closed]Python elif else syntaxError [关闭]
【发布时间】:2016-07-11 15:02:46
【问题描述】:

每当我尝试使用 else 和 elif 时,我都会收到该错误。

x=4
if x>0:
 print("positive")
elif x=4:
 print("equal")
else:
 print("negative")

消息错误:

File " '<'stdin'>' ", line 1 
elif x=4 :
       ^
SyntaxError: invalid syntax

  File "'<'stdin'>'", line 1
    else:
       ^
SyntaxError: invalid syntax

【问题讨论】:

  • elif x=4: -> elif x == 4:
  • 非常感谢老兄^^

标签: python if-statement syntax conditional-statements


【解决方案1】:

= 是一个赋值运算符。

== 是一个比较运算符。

您需要在elif 语句中使用比较运算符,如下所示:

x = 4
if x > 0:
    print("positive")
elif x == 4:
    print("equal")
else:
    print("negative")

【讨论】:

    【解决方案2】:

    那是因为您使用的是赋值运算符 = 而不是相等运算符 ==

    x=4
    if x>0:
     print("positive")
    elif x==4:
     print("equal")
    else:
     print("negative")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2017-07-03
      • 2012-09-01
      • 2014-06-30
      • 1970-01-01
      相关资源
      最近更新 更多