-1

Is this allowed syntax?

for bit in binary_string:
    is_zero = bit == '0'
    ...  

Edit: My IDE Python in terminal is throwing syntax error. I found it here: https://github.com/johnmee/codility/blob/master/ex-1-1-binarygap.py#L33

edit:

>>> N = 1004
>>> binary_string = str(bin(N))[2:]
>>> for bit in binary_string:
...     is = bit == '0'
  File "<stdin>", line 2
    is = bit == '0'
     ^
SyntaxError: invalid syntax
Jay Jung
  • 1,805
  • 3
  • 23
  • 46
  • Which IDE are you using ? – Umair Mohammad Apr 10 '18 at 06:31
  • sure it is. This assigns `is_zero` the value of the operation `bit=="0"`, so if `bit` was `"0"` before, `is_zero` is now `True`. This is perfectly valid python. What error is your IDE giving *exactly*? – Zinki Apr 10 '18 at 06:31
  • There's nothing wrong in the syntax, is_zero gets populated based on whether bit is equal to zero or not. It should work. – Mehul Jain Apr 10 '18 at 06:32
  • Check that you don't have an error further up your code, for example a missing single quote would detect an error on this line. Could you please show the exact error message? – cdarke Apr 10 '18 at 06:34
  • error message added – Jay Jung Apr 10 '18 at 06:35
  • 8
    `is` is a python reserved word, rename the variable! – cdarke Apr 10 '18 at 06:35
  • See https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator – cdarke Apr 10 '18 at 06:36
  • 1
    I'm going to downvote your question because you first said you used `is_zero` and then you showed you used `is`, which is a python keyword. Inconsistency like that is not help to anyone trying to answer your question. – cdarke Apr 10 '18 at 06:39
  • 1
    for future reference, it would be helpful if, when you have an error with your code, you actually posted the code that throws the error. The original sample you posted was perfectly fine and you failed to mention that you'd changed it to create the error you were seeing. Had you posted your actual code (with the `is`) originally, your question would have been solved in seconds. – Zinki Apr 10 '18 at 06:39
  • If you feel like `is` the variable name better suits here, then use `is_` to avoid confict with python keywords. – Abdul Niyas P M Apr 10 '18 at 06:40

2 Answers2

2

It is allowed, your problem is, that is is a reserved keyword, e.g.

foo is None

Rename your variable ;)

hellow
  • 12,430
  • 7
  • 56
  • 79
1

Yes, it is legal because the right hand side of = is an expression which returns a value. In this case, the value True or False. After the expression has been evaluated, the name is_zero is assigned to that value.

Your SyntaxError is raised because you are trying to assign to the protected word is.

timgeb
  • 76,762
  • 20
  • 123
  • 145