Assignment Condition in Python While Loop
Use break:
while True:
i = sys.stdin.read(1)
if i == "\n":
break
# etc...
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:
- Assigns
sys.stdin.read(1)
to a variablei
- Compares
i
to\n
- If the condition is validated, enters the
while
body in whichi
can be used