Assignment operators are a fundamental part of programming in Python. They allow you to store the results of an operation into a variable, making it easy to manipulate data and perform calculations. In this lesson, we'll learn about various assignment operators, their usage, and some common issues that may arise when using them.
The most basic assignment operator is the equals sign (=
). It assigns the right-hand side of the equation to the left-hand side variable.
x = 5
print(x) # Output: 5
Python provides shorthand assignment operators for common operations. These include +=
, -=
, *=
, /=
, %=
, and //=
. Each operator adds, subtracts, multiplies, divides, modulo, or floor divides the right-hand side value to the left-hand side variable respectively.
x = 5
x += 3
print(x) # Output: 8
You can also use multiple assignment operators (,
) to assign multiple variables at once.
a, b = 10, 20
print(a, b) # Output: 10 20
x = 5
y = x * 2
z = y + 3
print(x) # Output: 5
print(y) # Output: 10
print(z) # Output: 13
# Using shorthand assignment operator
x *= 2
x += 1
print(x) # Output: 9
a, b = 10, 20
c, d = a + b, a * b
print(a, b) # Output: 10 20
print(c, d) # Output: 30 200
What causes it: Mis-spelling or not defining a variable before using it.
# Bad code example that triggers the NameError
x + y
Error message:
NameError: name 'y' is not defined
Solution: Define the variable before using it or make sure to spell it correctly.
# Corrected code
y = 10
x + y
What causes it: Trying to perform an operation that doesn't make sense with a specific data type.
# Bad code example that triggers the TypeError
5 + "Hello"
Error message:
TypeError: can only concatenate str (not "int") to str
Solution: Convert the data type to a compatible one before performing the operation.
# Corrected code
str(5) + "Hello"
i
, j
, and k
in loops).Next steps: Practice using different types of assignment operators in various scenarios, and learn about other Python operators like comparison operators, logical operators, and bitwise operators.