簡體   English   中英

如何在終端中使用 python 編寫多行代碼?

[英]How can I write multi-line code in the Terminal use 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

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

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

如果你寫一個 \\,Python 會提示你用 ...(續行)在下一行輸入代碼,可以這么說。

要解決IndentationError: expected an indented block ,請將下一行放在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

出來了:

IndentationError:需要一個縮進塊

所以,當使用 while 循環時,下一行應該有縮進的塊(按 Tab 鍵)。

>>> i = 0
>>> while i < 10:
...     i += 1
...     print i 
... 
1
2
3
4
5
6
7
8
9
10
>>> 

只需復制代碼並將其粘貼到終端中,然后按回車鍵即可。 如果您這樣做,此代碼將完美運行:

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

1
2
3
4
5
6
7
8
9
10

使用python3 - <<'EOF'命令。

例如:

python3 - <<'EOF'
a=7
b=5
print(a+b)
EOF

12

Python 會自動檢測 for-next、while 等部分中的代碼塊。只需在某些代碼后放置一個 ':' <-- 冒號符號。

然后下一行前面會有一個繼續符號('...')而不是提示('>>>')

請記住按制表符以縮進要在塊中執行的代碼。 這將縮進該行並告訴 Python 后面的代碼是塊的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM