简体   繁体   English

为什么在 IF 语句后立即在 Python REPL 中收到无效语法错误?

[英]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.但是,它在 Python REPL 中给我一个无效的语法错误。

Why is it?为什么?

在此处输入图像描述

On Python 3.6.5 (x64), Windows 10 RS4在 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 ,正如 user2357112 所指出的,这种行为在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.循环体是缩进的:缩进是 Python 对语句进行分组的方式。 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;在实践中,您将使用文本编辑器为 Python 准备更复杂的输入; 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. REPL 一次只能读取和评估一个语句。 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.这是可能的,因为 REPL 无法决定第三行是继续if构造还是开始一个全新的语句。 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.在开始新的语句之前,您必须向 REPL 明确表示您之前的语句已完成。

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!在较旧的 python 版本中,print 被用作 print"ok",我看到你的操作系统是 windows 所以你可以直接从https://python.org/下载 python3 祝你有美好的一天!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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