Logo

Developer learning path

Python

Assignment Operators in Python

Assignment Operators

65

#description

Assignment operators are used to assign values to variables in Python.

There are several types of assignment operators in Python, and they include:

  1. = 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

  1. += 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

  1. -= 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

  1. *= 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

  1. /= 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)

  1. %= 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

  1. //= 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

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.