python - Invalid Syntax (For Loop Brackets) -


the following line of code outputs syntaxerror: invalid syntax

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

the next 1 works without errors. have no idea syntax error supposed here. asking out of curiosity. guess brackets prevent expression being evaluated.

for in range(-width,width): 

your parentheses confusing parser.

there couple of reasons have open paren after for, notably using tuple unpacking:

>>> (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 used in loads of places in python simple grouping, such when breaking long lines:

>>> s = ("this " ... "a awkward way " ... "to write " ... "long string " ... "over several lines") >>>  >>> s 'this awkward way write long string on several lines' 

so parser won't complain it.

however, know, for supposed read this:

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

which means grouping way, you're constructing invalid loop. essentially, yours reads there no in because it's grouped target_list parentheses. hope makes sense.


a way see more what's happening: write rest of loop (in expression_list) after close paren. clearer error how interpreting statement.

>>> (i in range(-width, width)) in range(-width, width): ...   print(i) ...    file "<stdin>", line 1 syntaxerror: can't assign comparison 

so let it, result of x in y boolean, cannot target of assignment. original error got because got : before found in, plain old invalid syntax, if wrote for x:.


Comments