Python assignment operators

Python Assignment Operators

In Python, the = (equal to) sign is defined as an assignment operator. It assigns the value of the Python expression on the right to the single variable on the left. In general programming (and specifically in Python), the = sign should not be confused with its use in mathematics, where it indicates that the expressions on either side are equal.

In addition to the simple assignment operators, Python provides several more advanced assignment operators. These are called accumulation or augmented assignment operators. In this chapter, we’ll learn how to use the augmented assignment operators defined in Python.

Consider the following Python statement:

a=10
b=5
a=a+b
print (a)

To someone new to programming but familiar with mathematics, the statement a=a+b might seem strange. How could a be equal to a+b? However, it’s important to emphasize again that the = symbol here is an assignment operator, not an operator that indicates equality between the left and right sides of the expression.

Because it’s an assignment operator, the expression on the right evaluates to 15, and this value is assigned to a.

In the statement a+=b, the two operators, + and =, can be combined into a single “+=” operator. This is called the addition and assignment operator. In a single statement, it adds “a” and “b” and assigns the result to the left operand, “a”.

+= is an augmented operator. It is also called the cumulative addition operator because it adds “b” to “a” and assigns the result back to a variable.

Python provides augmented assignment operators for all arithmetic and comparison operators.

Leave a Reply

Your email address will not be published. Required fields are marked *