Assignment Operators in Python
Assignment Operators
65
Assignment operators are used to assign values to variables in Python.
There are several types of assignment operators in Python, and they include:
- = operator: This is the most basic assignment operator in Python, and it assigns the value on the right side of the operator to the variable on the left side.
Example:
x = 10
y = "hello"
z = True
- += operator: This operator adds the value on the right side of the operator to the variable on the left side and assigns the result back to that variable.
Example:
x = 10
x += 5 # This is equivalent to x = x + 5
print(x) # Output: 15
- -= operator: This operator subtracts the value on the right side of the operator from the variable on the left side and assigns the result back to that variable.
Example:
x = 10
x -= 2 # This is equivalent to x = x - 2
print(x) # Output: 8
- *= operator: This operator multiplies the value on the right side of the operator with the variable on the left side and assigns the result back to that variable.
Example:
x = 5
x *= 3 # This is equivalent to x = x * 3
print(x) # Output: 15
- /= operator: This operator divides the variable on the left side of the operator by the value on the right side and assigns the result back to that variable.
Example:
x = 20
x /= 4 # This is equivalent to x = x / 4
print(x) # Output: 5.0 (Note that x is now a float)
- %= operator: This operator takes the modulus of the variable on the left side with the value on the right side and assigns the result back to that variable.
Example:
x = 17
x %= 5 # This is equivalent to x = x % 5
print(x) # Output: 2
- //= operator: This operator performs integer division of the variable on the left side with the value on the right side and assigns the result back to that variable.
Example:
x = 20
x //= 4 # This is equivalent to x = x // 4
print(x) # Output: 5
These assignment operators can help simplify your code by reducing the amount of code you need to write to perform simple operations.
March 25, 2023