0
In [1]: n = '4' != 'e'

In [2]: n
Out[2]: True

In [3]: while n = '4' != 'e':
  File "<ipython-input-12-1aa2b5c52181>", line 1
    while n = '4' != 'e':
            ^
SyntaxError: invalid syntax

The expression n = '4' != 'e' has a boolean True value in Python. However, when used in a while loop, Python 2.7 complains to parse it as the loop condition. Why is it so?

sherlock
  • 2,397
  • 3
  • 27
  • 44
  • 2
    You are assigning a variable in while loop. Instead use `while n:` or `while ('4' != 'e'):` as your condition. – Space Impact Sep 01 '18 at 07:24
  • I am not asking for an alternative. Asking why this construct doesn't work – sherlock Sep 01 '18 at 07:29
  • While statement expects an expression that returns a boolean value. What you did is an assignment operation that doesn't return a boolean value. You can have anything there so long as it boils down to a True or False. And assigning `n = expr` doesn't evaluate to a boolean value. As `while` doesn't check the `n` value but checks the return value of `n = expr` – Vineeth Sai Sep 01 '18 at 07:35
  • `while '4' != 'e'` will work. `n` is just a variable. – Tom Wojcik Sep 01 '18 at 07:36
  • in c++ this would work as `((n='4')!='e')`, so there is no python equivalent of it? @VineethSai – jkhadka Sep 01 '18 at 07:56
  • 1
    It doesn't work because `n = something` is not an [expression](https://docs.python.org/3/reference/expressions.html), it is an [assignment statement](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements). A hint is how there is no `Out[1]`. The statement has no value, it only sets bindings such as `n` getting set to `True`. – Yann Vernier Sep 01 '18 at 07:57

0 Answers0