如何在终端中使用 python 编写多行代码?

新手上路,请多包涵

如何在 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.
>>>

例如示例:

 i = 0

while i < 10:
    i += 1
    print i

在终端中,我不知道如何在 python shell 中换行:

我测试了 Control + EnterShift + EnterCommand + Enter ,它们都错了:

 >>> while i < 10:
... print i
  File "<stdin>", line 2
    print i
        ^
IndentationError: expected an indented block

原文由 aircraft 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 937
2 个回答

只需复制代码并将其粘贴到终端中,然后按回车键。如果您这样做,此代码将完美运行:

    i = 0
..
.. while i < 10:
..     i += 1
..     print(i)
..

1
2
3
4
5
6
7
8
9
10

原文由 developer_hatch 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以添加尾随反斜杠。例如,如果我想打印一个 1:

 >>> print 1
1
>>> print \
... 1
1
>>>

如果你写一个 \,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

原文由 Wasi Ahmad 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题