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
After:
while (line := file.readline()):
# process line
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)