Python evolves over time. Mostly for the good as it adds features that make things easier and more sensible. One of those is the assignment expression. If you have a C background, you are used to assignment expressions. In C, x = 10
both assigns the value 10 to x and also returns the value 10 so you can use it in logical expressions and the like.
In Python, this is not the case. In Python, x = 10
assigns 10 to x but does not have a value that you can use in further expressions. The new assignment expression, :=
, works like the C assignment. This means you can write code like:
while i := input("Enter your name: "):
print(f"You name is {i}")
instead of:
while True:
i = input("Enter your name: ")
if i:
print(f"Your name is {i}")
else:
break
I don’t know about you, but I find the code using the walrus operator to be much more clear.
This was not without controversy but in my opinion, this change is a good one. It has some concrete coding advantages and gets Python closer to other mainstream languages. PEP 572 has some examples and discussion that is worth reading.