for loop in Python called from bash

5k views Asked by At

I am executing a Python (2.6.6) command directly from bash, like this :

bash-4.1$ python -c "for i in range(4) : print('a')"

which outputs

a
a
a
a

However, when I add something before the for loop, I get a SyntaxError:

bash-4.1$ python -c "myChar = 'a'; for i in range(4) : print(myChar)"
  File "<string>", line 1
    myChar = 'a'; for i in range(4) : print(myChar)
                    ^
SyntaxError: invalid syntax

no matter what I put before the semicolon. However,

bash-4.1$ python -c "i = 1; print i"

works just fine.

Any idea of what's happening here?

1

There are 1 answers

1
AudioBubble On

Use a here document if you want to write Python code in a shell script.

$ python3.4 <<EOF
myChar = 'a'
for i in range(4):
    print(myChar)
EOF 

Output:

a
a
a
a

Read PEP 0008 and PEP 0020 about Python style.