Reputation: 38392
I am a python newbie and have a question. Why can a if allow a brackets and not for.
if (1==2):
for (i in range(1,10)):
while (i<10):
First one and third one are valid syntax but not second one.
File "<stdin>", line 2
for (i in range(1,10)):
^
Upvotes: 4
Views: 356
Reputation: 60004
Because for (i in range(1,10))
isn't syntactically correct.
Lets assume (i in range(1,10))
was parsed anyway, it would return a boolean. So then you're trying to say for True
or for False
, and booleans can't be iterated, and it's invalid syntax.
The reason why your other examples work is because they expect a boolean, which is what is returned from 1 == 2
and i < 10
Upvotes: 7
Reputation: 383846
if
expects a value (True
of False
). You can put parenthesis around any values: (1) + (1)
for VAR in LIST
is a fixed syntax which does not expect a value single value, but rather two inputs:
So why would the Python language allow extra parenthesis there?
As someone had pointed on a now deleted answer (why?), this is the syntax for the for
statement: http://docs.python.org/3/reference/compound_stmts.html#the-for-statement :
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
Upvotes: 1