Assignment Condition in Python While Loop

tekknolagi picture tekknolagi · Oct 16, 2011 · Viewed 17.4k times · Source

In C, one can do

while( (i=a) != b ) { }

but in Python, it appears, one cannot.

while (i = sys.stdin.read(1)) != "\n":

generates

    while (i = sys.stdin.read(1)) != "\n":
         ^
SyntaxError: invalid syntax

(the ^ should be on the =)

Is there a workaround?

Answer

Mark Byers picture Mark Byers · Oct 16, 2011

Use break:

while True:
    i = sys.stdin.read(1)
    if i == "\n":
       break
    # etc...