简体   繁体   中英

Why am I getting an invalid syntax error in Python REPL right after IF statement?

I think this is perfectly valid.

if False:
    print(1)
print(2)

However, it gives me an invalid syntax error in Python REPL.

Why is it?

在此处输入图像描述

On Python 3.6.5 (x64), Windows 10 RS4

As pointed out by user2357112, this behaviour is explained in https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming ,

The body of the loop is indented: indentation is Python's way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

The REPL can only read and evaluate one statement at a time. You entered two statements at once.

This is possible because the REPL cannot decide if the third line is going to continue the if construction or start a whole new statement. It has to assume the former to allow indented blocks at all.

You have to make it clear to the REPL that your previous statement is finished before starting a new one.

Wrong version seems to be the most possible since, in the error it shows print. In the older python versions, print was used as print"ok", I see your operating system is windows so you can just directly download python3 from https://python.org/ have a nice day!

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