2.6. Variable#

2.6.1. Walrus Operator: Assign a Variable in an Expression#

The walrus operator (:=) in Python 3.8 and above allows you to assign a variable in an expression. The walrus operator is useful when you want to:

  • debug the components in an expression

  • avoid repeated computations

In the code below, I use the walrus operator to assign a value to r when getting the circumference of a circle, which is then used to find the area of the circle.

from math import pi

d = 4
# without Walrus operator
circumference = (d / 2) * 2 * pi
area = (d / 2) * pi**2 # d/2 is computed twice