Assignment Operators

Assignment operators are used to assign values to variables in Python. They are essential for storing data and updating values during program execution. These operators make code shorter and more efficient when performing calculations and reassigning values.

Understanding assignment operators is important for writing clean and optimized Python programs.

SIMPLE ASSIGNMENT OPERATOR

The simple assignment operator is represented by the equals sign.

Symbol: =

It assigns the value on the right side to the variable on the left side.

Example:

x = 10
name = “Hira”

Here, the value 10 is assigned to x, and the text Hira is assigned to name.

ADDITION ASSIGNMENT OPERATOR

Symbol: +=

This operator adds a value to the existing variable and assigns the result back to the same variable.

Example:

x = 5
x += 3

Now x becomes 8.

SUBTRACTION ASSIGNMENT OPERATOR

Symbol: -=

This subtracts a value from the variable and assigns the result.

Example:

x = 10
x -= 4

Now x becomes 6.

MULTIPLICATION ASSIGNMENT OPERATOR

Symbol: *=

This multiplies the variable by a value and assigns the result.

Example:

x = 6
x *= 2

Now x becomes 12.

DIVISION ASSIGNMENT OPERATOR

Symbol: /=

This divides the variable by a value and assigns the result.

Example:

x = 10
x /= 2

Now x becomes 5.0.

FLOOR DIVISION ASSIGNMENT OPERATOR

Symbol: //=

Example:

x = 10
x //= 3

Now x becomes 3.

MODULUS ASSIGNMENT OPERATOR

Symbol: %=

Example:

x = 10
x %= 3

Now x becomes 1.

EXPONENT ASSIGNMENT OPERATOR

Symbol: **=

Example:

x = 2
x **= 3

Now x becomes 8.

WHY ASSIGNMENT OPERATORS ARE IMPORTANT

Assignment operators help update variable values efficiently. They reduce the need to write longer expressions and make the code more readable.

Mastering assignment operators allows you to manage and manipulate data smoothly while building Python programs.

Home » PYTHON FUNDAMENTALS (PYF) > Operators > Assignment Operators