Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write multi-line code in the Terminal use python?

How can I write multi-line code in the 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.
>>> 

such as a sample example:

i = 0

while i < 10:
    i += 1
    print i 

In the terminal I don't know hot to line feed in the python shell:

I tested the Control+Enter, and Shift+Enter, and Command+Enter, they all wrong:

>>> while i < 10:
... print i 
  File "<stdin>", line 2
    print i 
        ^
IndentationError: expected an indented block
like image 774
aircraft Avatar asked Jun 20 '17 04:06

aircraft


3 Answers

You can add a trailing backslash. For example, if I want to print a 1:

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

If you write a \, Python will prompt you with ... (continuation lines) to enter code in the next line, so to say.

To resolve IndentationError: expected an indented block, put the next line after while loop in an indented block (press Tab key).

So, the following works:

>>> i=0
>>> while i < 10:
...   i+=1
...   print i
... 
1
2
3
4
5
6
7
8
9
10
like image 158
Wasi Ahmad Avatar answered Oct 05 '22 09:10

Wasi Ahmad


There comes out:

IndentationError: expected an indented block

So, when use the while loop, the next line should have the indented block(press Tab key).

>>> i = 0
>>> while i < 10:
...     i += 1
...     print i 
... 
1
2
3
4
5
6
7
8
9
10
>>> 
like image 25
aircraft Avatar answered Oct 05 '22 09:10

aircraft


Just copy the code and past it in the terminal, and press return. This code works perfect if you do that:

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

1
2
3
4
5
6
7
8
9
10
like image 38
A Monad is a Monoid Avatar answered Oct 05 '22 09:10

A Monad is a Monoid