Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an inline for loop in python after another instruction?

Starting with for works

root@messagerie-secours[10.10.10.19] /home/serveur # python -c "for x in xrange(10):print x;"
0
1
2
3
4
5
6
7
8
9
root@messagerie-secours[10.10.10.19] /home/serveur # 

If you have for in the middle, it's a syntax error :

root@messagerie-secours[10.10.10.19] /home/serveur # python -c "a=2;for x in xrange(10):print x;"
  File "<string>", line 1
    a=2;for x in xrange(10):print x;
          ^
SyntaxError: invalid syntax
root@messagerie-secours[10.10.10.19] /home/serveur #

Is it possible to get rid of that syntax error ?

like image 587
ychaouche Avatar asked May 11 '26 09:05

ychaouche


1 Answers

Woo, plenty of solutions! here some others:

python -c 'print "\n".join(map(str, xrange(10)))'

python <<"EOF"
for x in range(10):
  print x
EOF

echo $'a=12\nfor x in range(a): print x' | python
like image 153
bufh Avatar answered May 14 '26 00:05

bufh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!