【问题标题】:if statement fails when used after semi-colon separator在分号分隔符后使用 if 语句失败
【发布时间】:2019-08-22 02:10:44
【问题描述】:

当我在分号(用作语句分隔符)后使用单行 if 语句时,我不明白为什么 Python 会出错。

没关系:

if True: print("it works")
#### it works

但这会产生语法错误:

a=1; if True: print("it should work?")
#### SyntaxError: invalid syntax

我使用 Python3 和 Spyder。

感谢您的任何解释!

【问题讨论】:

  • 这不适用于任何compound statement,因为子句标题需要在它自己的行上。

标签: python if-statement semicolon-inference


【解决方案1】:

分号只能用于连接“小语句”,不包括if 语句。来自https://docs.python.org/3/reference/grammar.html

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)

[...]
compound_stmt: if_stmt | [...]

【讨论】:

  • 谢谢,不知道!
  • 显然,鉴于 Python 使用缩进,if foo: x=1; y=2 之类的东西是模棱两可的。我怀疑a=1; if True: print("it should work") 中没有歧义。但是,可能不值得使语法复杂化来支持它。 (或者考虑到 Python 使用 LL(1) 语法的自我约束,这可能是不可能的。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多