在使用分号分隔符后使用if语句失败

问题描述 投票:0回答:1

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

还行吧:

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

但这会产生语法错误:

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

我使用Spyder的Python3。

谢谢你的解释!

python if-statement semicolon-inference
1个回答
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 | [...]
© www.soinside.com 2019 - 2024. All rights reserved.