Assignment Condition in Python While Loop

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 variable i
  • Compares i to \n
  • If the condition is validated, enters the while body in which i can be used

Leave a Comment