Trusted answers to developer questions

What are assignment operators in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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)

RELATED TAGS

assignment operators
python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?