如何在 python REPL 中编写多行代码?:
aircraftdeMacBook-Pro:~ ldl$ python
Python 2.7.10 (default, Jul 30 2016, 19:40:32)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Run Code Online (Sandbox Code Playgroud)
例如示例:
i = 0
while i < 10:
i += 1
print i
Run Code Online (Sandbox Code Playgroud)
在终端中,我不知道在 python shell 中热换行:
我测试了Control+ Enter、Shift+Enter和Command+ Enter,它们都错了:
>>> while i < 10:
... print i
File "<stdin>", line 2
print i
^
IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)
您可以添加尾部反斜杠。例如,如果我想打印一个 1:
>>> print 1
1
>>> print \
... 1
1
>>>
Run Code Online (Sandbox Code Playgroud)
如果你写一个 \,Python 会提示你用 ...(续行)在下一行输入代码,可以这么说。
要解决IndentationError: expected an indented block,请将 while 循环后的下一行放在缩进块中(按 Tab 键)。
因此,以下工作:
>>> i=0
>>> while i < 10:
... i+=1
... print i
...
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
只需复制代码并将其粘贴到终端中,然后按回车键即可。如果您这样做,此代码将完美运行:
i = 0
..
.. while i < 10:
.. i += 1
.. print(i)
..
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)