What are assignment operators in Python?

Assignment operators are used to assign a value to a variable.The most commonly used assignment operator is =.

Assignment operators are always in-fix.

svg viewer

Types of assignment operators

operator description example
+= It adds the right operand to the left operand and stores the result in the left operand. x += y is equivalent to x = x + y
-= It subtracts the right operand from the left operand and stores the result in the left operand. x -= y is equivalent to x = x - y
*= It multiplies the right operand with the left operand and stores the result in the right operand. x *= y is equivalent to x = x * y
/= It divides the left operand by the right operand and stores the result in the left operand. x /= y is equivalent to x = x / y
%= It takes the module of the left operand and, using the right operand, stores the result in the left operand. x %= y is equivalent to x = x % y
**= It raises the exponential power of the left operand to the value of the right operand, storing the result in the left operand. x **= y is equivalent to x = x ** y

Example

# assignment operators
x = 5
y = 6
print ('x = ',x,' and y = ',y)
x += y ## equivalent to x = x + y
print ('x += y is equal to ',x)
print ('x = ',x,' and y = ',y)
x -= y ## equivalent to x = x - y
print ('x -= y is equal to ',x)
print ('x = ',x,' and y = ',y)
x *= y ## equivalent to x = x * y
print ('x *= y is equal to ',x)
print ('x = ',x,' and y = ',y)
x /= y ## equivalent to x = x / y
print ('x /= y is equal to ',x)
print ('x = ',x,' and y = ',y)
x %= y ## equivalent to x = x % y
print ('x %= y is equal to ',x)
print ('x = ',x,' and y = ',y)
x **= y ## equivalent to x = x % y
print ('x **= y is equal to ',x)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved