The Walrus operator in Python is pretty straightforward. With it, you can assign a value to a variable and immediately use it. For example:
if (sum := 10+5) > 10:
print("This should be printed)
In this example, the variable sum
is assigned the value 15
and then we use it to evaluate if 15 > 10
. As this is true, we should see the content of the print statement.
Be careful about the parenthesis! If we have something like this:
if sum := 10 + 5 > 10:
print("Is this going to be printed?")
We will have the sum
is equal to True
and the print statement will be executed but the value of sum won't be 15
.
You can see an explanation of the Walrus operator and more of this content at my YouTube channel: https://www.youtube.com/watch?v=cdD313keRW8&ab_channel=DavidArmend%C3%A1riz
Top comments (0)