DEV Community

qing
qing

Posted on

TIL: Python's walrus operator `:=` can simplify while loops (2026)

TIL: Python's walrus operator := can simplify while loops
I recently discovered Python's walrus operator (:=) and it's been a game-changer for simplifying while loops. The := operator is an assignment operator that allows you to assign a value to a variable as part of a larger expression. This is particularly useful in while loops where you need to assign the result of a function or expression to a variable and then check its value.

Before:

while True:
    line = file.readline()
    if not line:
        break
    # process line
Enter fullscreen mode Exit fullscreen mode

After:

while (line := file.readline()):
    # process line
Enter fullscreen mode Exit fullscreen mode

In the after example, the := operator assigns the result of `


Follow me on Dev.to for daily Python tips and quick guides!


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)