当我在分号(用作语句分隔符)后使用单行if
语句时,我不明白为什么我在使用Python时出错。
还行吧:
if True: print("it works")
#### it works
但这会产生语法错误:
a=1; if True: print("it should work?")
#### SyntaxError: invalid syntax
我使用Spyder的Python3。
谢谢你的解释!
分号只能用于加入“小语句”,不包括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 | [...]