Skip to main content

Assignment Operators

An assignment operator gives a variable its value:

Assignment Operators Table

main.py
# =    x = 5       x = 5
# +=   x += 3      x = x + 3
# -=   x -= 3      x = x - 3
# *=   x *= 3      x = x * 3
# /=   x /= 3      x = x / 3
# %=   x %= 3      x = x % 3
# //=  x //= 3     x = x // 3
# **=  x **= 3     x = x ** 3
# &=   x &= 3      x = x & 3
# |=   x |= 3      x = x | 3
# ^=   x ^= 3      x = x ^ 3
# >>=  x >>= 3     x = x >> 3
# <<=  x <<= 3     x = x << 3
# :=   print(x := 3)   x = 3; print(x)

The Walrus Operator

The := operator, nicknamed the "walrus operator", arrived in Python 3.8. With it, you can give a variable a value in the middle of a larger expression:

Example

Here the count variable gets its value of 5 right inside the if statement:

Prompt
Write a Python program that creates a list of numbers [1, 2, 3, 4, 5], uses the walrus operator := to assign the length to count inside an if statement, and prints a message if count is greater than 3.
Output: complete Python program