18

Say I want to print 0 through 9.

I type in for i in range(10): print(i), press enter, and terminal shows ..., waiting for further statements.

So I have to press enter again to have the numbers printed.

>>> for i in range(10): print(i)
...

How can I have the number printed without having to press enter twice?

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80

5 Answers5

24

Just type the two returns and move on. But since you ask, this only needs one Enter:

exec("for i in range(10): print(i)")
alexis
  • 48,685
  • 16
  • 101
  • 161
7

"alt+enter" I was working in ipython and facing the same problem as yours. upon trying various combinations from keyboard, this one finally worked

Paarmita
  • 81
  • 1
  • 1
2

You can use the Shift+Enter to end the function or loop which continues next line as below:

enter image description here

Flickerlight
  • 904
  • 8
  • 18
Guest User
  • 31
  • 1
0

Convert your for-loop into a so-called list comprehension (you don't need eval / exec and wrap the whole thing in a string as the current top answer suggests):

In [1]: [i for i in range(3)]
Out[1]: [0, 1, 2]

You can also keep your print() statement if you want it on multiple lines, but the return value (None) will be put in the array that is returned, so you'll get this:

In [2]: [print(i) for i in range(3)]
0
1
2
Out[2]: [None, None, None]

To suppress that final output line, you can add a semicolon:

In [3]: [print(i) for i in range(3)];
0
1
2

So much for ipython3, but perhaps more usefully, what about command-line usage? You can't do python3 -c 'import sys; for line in sys.stdin: print(line)' but you can use list comprehension:

$ python3 -c '[print(i) for i in range(3)]'
0
1
2

So if you want to run a bit of python over each line:

$ cat inputfile
two
examples
$ cat inputfile | python3 -c 'import sys; [print(line.strip().upper()) for line in sys.stdin]'
TWO
EXAMPLES

(You can replace cat infile | with <infile but this seemed more accessible for those not familiar with Bash syntax, and those who are familiar can trivially replace it.)

Luc
  • 5,339
  • 2
  • 48
  • 48
0

You can execute the for statement without using the exec() by pressing enter to go to the next line and then pressing ctrl + d

Salman
  • 9
  • 4