Python - What's The Difference Between "=" And "=="?
Solution 1:
The difference between the two are:
==
is the operator to check if two objects are equivalent.=
is the operator to assign value(s) to a variable.
Example:
>>>a = 5# `=` operator>>>a
5
>>>a == 5# `==` operator
True
>>>
Also the reason why your code returned an error, is because you already have a variable called a
outside the function, so there you want to assign it again, it won't work.
Thanks to @SpencerWieczorek for a much better explanation of the part of explanation below the code:
Note: The second example the local a and the global a are entirely different variables. In order to use the global a you defined you would want to add global a at the start of the function. The local variable doesn't have anything to do with the global one and is not the reason for the error.
Solution 2:
To understand the difference between these two you first need to understand the difference between comparison operators and assignment operators
=
assignment operator
This will assign a given value with another value. There is also +=
, -=
, *=
, /=
... which perform value assignments in place adding, subtracting, multiplying, or dividing the value on the right to the value on the left. *More explanation and information can be found either in the documentation or in the link I provided.
a = 5
b = 2
print(a, b)
#5 2
b += 10
print(b)
#12
==
comparison operator
This compares two python objects and returns True
if two variables result in the same value. (not to be mistaken with is
which compares if two variables point to the same object) There's also !=
, <>
, >
, <
... which determine if two objects results are not equal, greater, or lesser.
a == 5#Truea == b
#False
Post a Comment for "Python - What's The Difference Between "=" And "=="?"