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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With