Is Python sensitive to extra parentheses?

This snippet worked great

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

Studied the loops and they worked great

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 the error "SyntaxError: invalid syntax"

I understand that the outer bracket makes the loop crazy (error), but what part of the syntax is it breaking ? it worked perfectly during the cycle

+4
source share
2 answers

syntax for(simplified)

for <variable(s)> in <expression>

more precisely :

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

as you put in brackets <variable> in <expression>, the syntax becomes invalid.

forand inmust be present at the same level of nesting.

while :

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

, , Python

+5

. while, , :

while <condition>:

, , . for:

for <variable> in <expression>:

expression , .

+2

Source: https://habr.com/ru/post/1689151/


All Articles