The assignment operator is used to pass the value on the right to the variable (or constant) on the left;
you can directly give the value on the right to the variable on the left, or you can perform some operations
and then give it to the variable on the left. Such as addition, subtraction, multiplication and division,
function calls, logical operations, etc.
The most basic assignment operator in Python is the equal sign =; combined with other operators, = also
expands to more powerful assignment operators.
Python - Basic Assignment Operator
= is the most common and basic assignment operator in Python. It is used to assign the value of an expression
to another variable. See the following example:
a_1 = 100 #Assign an integer to a variable a_1
b_1 = 47.5 #Assign a float to a variable b_1
c_1 = "Welcome to Free Learning Platform" #Assign a string to a variable c_1
a_2 = a_1 #Assign the value of one variable a_1 to another variable a_2
b_2 = b_1 #Assign the value of one variable b_1 to another variable b_2
sum_1 = 25 + 46 #Assign the value of some operations such as + to variables
sum_2 = n1% 6 #Assign the value of some operations such as % to variables
s_2 = str (1234) #Convert numbers to strings
s_3 = str (100) + "abc"
Python - Continuous Assignment
The assignment expression in Python also has a value, and its value is the value assigned, or the value of the
variable on the left; if the value of the assignment expression is assigned to another variable, this forms
continuous assignment. For example:
a = b = c = 100
= Right associative, we analyse this expression from right to left:
c = 100 means that 100 is assigned to c, so the value of c is 100; at the same time, the value of the
subexpression c = 100 is also 100. b = c = 100 means that the value of c = 100 is assigned to b, so the
value of b is also 100. By analogy, the value of a is also 100. So, the result is that the values of the
three variables a, b, and c are all 100.
Python in = And ==
= And == are two different operators. = is used to assign values, and == is used to determine whether
the values on both sides are equal.
Python - Extended Assignment Operator
= can also be combined with other operators (including arithmetic operators, bit operators, and logical operators)
to expand into more powerful assignment operators, as shown in table below. The extended assignment operator
will make the writing of assignment expressions more convenient.
Note that this assignment operator can only assign values to existing variables, because the
variable itself needs to participate in the operation during the assignment. If the variable
is not defined in advance, its value is unknown and cannot participate in the operation.
For example, the following is wrong:
n += 10
This expression is equivalent to n = n + 10, n is not defined in advance, so it cannot
participate in addition.