简体   繁体   中英

if statement fails when used after semi-colon separator

I don't understand why I'm having an error with Python when I use a single-line if statement after a semicolon (used as a statement separator).

This is ok:

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

But this gives a syntax error:

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

I use Python3, with Spyder.

Thanks for any explanation!

Semicolons can only be used to join "small statements", which don't include if statements. From 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 | [...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM