It's very simple, =
is an assignment operator , you should only use it to save a value to a variable. The operand on the left side must always be a variable, nothing more. The right operand accepts a value from a literal, a variable (another one or the same, although it does not make much sense to be the same) or an expression that will be executed and its result will generate a value, and the final value obtained will be saved in the variable.
==
is a comparison operator . The two sides can be variable, literal or different expressions. Always try to identify that the final value obtained on the left side is equal to the final value obtained on the right side. The result of the comparison operation will be Boolean, that is, it will be True
or False
. It is very common to use a if
or while
, but it does not have to be this way, it can be used anywhere that expects a boolean, it can even be used on the right side of =
and assign this value to a variable or can use to print something or pass as argument in a function.
The concept holds true for essentially any language.
x = 1 == 2
This is an example where x
will be False
because it is assigning in the variable what is on the right side that is a comparison if they are equal values, which obviously are not. To understand a little better we can do this, although unnecessary by precedence the associativity of operators:
x = (1 == 2)