What are Assignment Operators in Python

What are Assignment Operators in Python 

In Python, the assignment operator is used to assign a value to a variable. For example, the statement x = 5 assigns the value 5 to the variable x.



In addition to the standard assignment operator (=), Python provides a set of shorthand assignment operators that combine assignment with an arithmetic or logical operation. These operators are useful for writing concise and efficient code.


For example, the statement x += 5 is equivalent to x = x + 5. It adds the value 5 to the current value of x, and then assigns the result back to x. Similarly, the statement x *= 3 is equivalent to x = x * 3, which multiplies the current value of x by 3 and assigns the result back to x.


Here are some examples of assignment operators in Python:


Copy code

# addition assignment

x = 5

x += 3  # x = x + 3 = 8


# subtraction assignment

x = 5

x -= 3  # x = x - 3 = 2


# multiplication assignment

x = 5

x *= 3  # x = x * 3 = 15


# division assignment

x = 10

x /= 5  # x = x / 5 = 2.0


# modulus assignment

x = 10

x %= 3  # x = x % 3 = 1


# exponent assignment

x = 2

x **= 3  # x = x ** 3 = 8

As you can see, these assignment operators allow us to perform an operation on a variable and then assign the result back to the same variable in a single statement. This can make our code more concise and easier to read.


Overall, assignment operators are an important part of Python, and they can be used to perform a wide range of operations on variables in your code.

Comments