Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sensitive to extra parenthesis?

This snippet worked fine

if True: print "just True"
if (True): print "(True)"

Was studying loops and these worked fine

for i in range(1, 3):
    print i

i = 0
while i < 3: # without paranthesis
    print i
    i = i + 1

i = 0
while (i < 3): # with paranthesis
    print i
    i = i + 1

When I tried

for (i in range(1, 3)):
    print i

I get an error "SyntaxError: invalid syntax"

I do understand the outside parenthesis is making for loop go crazy (error) but which part of the syntax am I violating? it worked fine in while loop

like image 980
Srinath Ganesh Avatar asked Mar 07 '23 15:03

Srinath Ganesh


2 Answers

syntax of for is (simplified)

for <variable(s)> in <expression>

more precisely:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

since you're parenthesizing <variable> in <expression>, the syntax becomes invalid.

for and in must be present at the same nesting level.

syntax of while is much simpler:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

thus allows parentheses, although not necessary in Python

like image 140
Jean-François Fabre Avatar answered Mar 20 '23 04:03

Jean-François Fabre


You can't just lob on extra parenthesis anywhere you want. The while syntax, generally stated, is:

while <condition>:

Here, you're just surrounding a condition with parenthesis, which is fine, as you saw yourself. The for loop's syntax is:

for <variable> in <expression>:

You could surround the expression in parenthesis, but no arbitrary parts of the syntax.

like image 22
Mureinik Avatar answered Mar 20 '23 03:03

Mureinik