Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid Syntax (For Loop brackets/parentheses)

The following line of code outputs SyntaxError: invalid syntax

for (i in range(-WIDTH,WIDTH)):

The next one works without errors. I have no idea what the syntax error is supposed to be here. So I am just asking out of curiosity. My guess is that the brackets prevent the expression from being evaluated.

for i in range(-WIDTH,WIDTH):
like image 374
Philipp Braun Avatar asked Apr 13 '26 10:04

Philipp Braun


1 Answers

Your parentheses are essentially just confusing the parser.

There are a couple of reasons you could have an open paren after a for, most notably using tuple unpacking:

>>> for (x, y) in zip(range(5), range(6, 11)):
...   print(x, '->', y)
... 
0 -> 6
1 -> 7
2 -> 8
3 -> 9
4 -> 10

Additionally, parens can be used in loads of places in Python for simple grouping, such as when breaking up long lines:

>>> s = ("This is "
... "a really awkward way "
... "to write a "
... "long string "
... "over several lines")
>>> 
>>> s
'This is a really awkward way to write a long string over several lines'

So the parser won't really complain about it.

However, as you know, for is supposed to read like this:

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

Which means that by grouping this way, you're constructing an invalid loop. Essentially, yours reads that there is no in because it's grouped into the target_list by your parentheses. Hope this makes sense.


A way to see more clearly what's happening: write the rest of your for loop (in expression_list) after your close paren. Then you will get a clearer error about how it is interpreting this statement.

>>> for (i in range(-WIDTH, WIDTH)) in range(-WIDTH, WIDTH):
...   print(i)
... 
  File "<stdin>", line 1
SyntaxError: can't assign to comparison

So it will let you do it, but the result of x in y will be a boolean, which cannot be the target of an assignment. The original error you got is because it got to your : before it found your in, which is plain old invalid syntax, as if you just wrote for x:.

like image 174
Two-Bit Alchemist Avatar answered Apr 16 '26 01:04

Two-Bit Alchemist



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!