Python Assignment Operators

Assignment Operators in Python

The assignment operators in Python are used to assign values to the operators. 

Python allows a lot of flexibility in assigning multiple operators to the variables at once by making it a very simple one-line syntax.

Example:

>>>a= 1 #assigning a value to the variable 
>>>print(a)

Output:1 

Here, we declare a single variable ‘a’ and assign a value ‘1’ to it. Then we use the print function to get its output.

Example:

>>>a, b, c= 1, 2, 3 #assigning values to multiple variables
>>>print(a)
>>>print(b)
>>>print(c)

Output:

1 
2
3

Here we declare three variables a, b, c and assign values 1, 2 and 3 to them respectively and then print them.

Note: It is important to keep in mind that the number of variables declared is always equal to the number of values provided. Otherwise, this will lead to an error stating that there are not enough values to unpack.

Example:>>>a, b, c, d= 1, 2, 3 #taking extra variable d

Output:ValueError: not enough values to unpack

This example is similar to the previous example except that here instead of taking just a, b and c we also take a variable d which remains unassigned because of there not enough values.

This gives us a value error.


Compound Assignment Operator: 

When the assignment operator is combined with some other operators like arithmetic, etc then it is known as a compound assignment operator. It is used as a shorthand notation for a different combination of operators. For instance, the expression x +=11 means simply x = x+11. The available compound assignment operators are:

  • +=
  • -=
  • *=
  • /=
  • %=
  • //=
  • **=
  • &=
  • |=
  • ^=
  • >>=
  • <<=

Example:

>>>x=10
>>>x += 11 #using the compound assignment operator 
>>>x

Output: 21

In the above code refers take x equals to 10 then in the next line we use the compound assignment operator as x+ = 11 which means x= x+11 thus the output is 10+11 i.e. 21.

Note: However, increment and decrement operators are not applicable in Python due to this functionality as it treats ++a as +(+a). 

Example:

>>>x =4
>>>x &= 5 #x= x&5
>>>print(x)

Output: 4

In this example, we take x as 4. Then use the compound assignment operator of & as x &= 5 which means x = x & 5 and since x is 4 i.e. we are using the & operator with 4 and 5 and thus get the answer 4. 

Leave a Comment

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