2

Assuming I pass a oneliner like for i in range(0,3):print "a";print "b" to python -c, how can I limit the scope (not a good word, but the best I can think of) of the for loop to the first print, i.e. make the invokation print

a
a
a
b

instead of

a
b
a
b
a
b

Placing brackets around the first print or the for loop and the first print causes SyntaxError: invalid syntax.

Using identation characters fails due to

> python -c 'for i in range(0,3):\n  print "a"\nprint "b"'
  File "<string>", line 1
    for i in range(0,3):\n  print "a"\nprint "b"
                                               ^
SyntaxError: unexpected character after line continuation character

maybe I'm doing it wrong (the use uncommon use of ; is much more intuitive but causes the problem I try to solve with this question).

The described outputs are examples, I'm not seeking for other solution to printing aaab.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
  • 1
    When you write `'\n'` the shell doesn't interpret the escape sequence and Python sees literally backslash-n. Use `$'...'` string syntax to get the shell to pass newlines: `python -c $'for i in range(0,3):\n print "a"\nprint "b"'` – John Kugelman Jul 05 '18 at 00:06
  • 2
    You could use a comprehension, for instance: `[print('a') for i in range(0, 3)]; print('b')` –  Jul 05 '18 at 00:07
  • @wowserx ditto on list comprehension. Though this only works on Python 3 where `print` acts as a function. – SamuelN Jul 05 '18 at 16:26
  • to do it in python 2, `from __future__ import print_function`. –  Jul 06 '18 at 13:54

0 Answers0