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?
You initiate the loop with the while keyword, then set the condition to be any conditional expression. A conditional expression is a statement that evaluates to True or False . As long as the condition is true, the loop body (the indented block that follows) will execute any statements it contains.
You can pretty well use it anywhere a normal expression can be used (that comma inside your function calls is not a comma operator, for example) and it's very useful in writing compact source code, if that's what you like. In that way, it's part of the family that allows things like: while ((c= getchar()) !=
The while loop is used when we don't know the number of times it will repeat. If that number is infinite, or the Boolean condition of the loop never gets set to False, then it will run forever.
No. Assignment in Python is a statement, not an expression.
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's now possible to capture an expression value (here sys.stdin.read(1)
) as a variable in order to use it within the body of while
:
while (i := sys.stdin.read(1)) != '\n': do_smthg(i)
This:
sys.stdin.read(1)
to a variable i
i
to \n
while
body in which i
can be usedUse break:
while True: i = sys.stdin.read(1) if i == "\n": break # etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With