Python Forum

Full Version: Equality in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

what is the actual difference between

=
and
==

I have some trouble understanding the actual meaning of theses 2 operators.

Could someone explain it in a simple way?
Single "=" makes things equal. And "==" compares to see if they are equal.

one = 1
vs
if one == 1:
= isn't equality, it's assignment - i.e. assigning a value to a variable. a = 1, for example, is a statement. It doesn't return a value; it just sets the value of a to 1.

== checks whether the values on the left hand and right hand sides are equal. 1 == 2, for example, is an expression. It does return a value (i.e. False in this case) and can be used in other expressions.
An exemple with num%2==0

liist=[0,1,2,3,4,5,6,7,8,9,10]
summ=0

for num in liist:
    if num%2==0:
        print(f'that\'s a even number : {num}')
    else:
        print(f'That\'s an odd number : {num}')
        


here if num%2==0 why cant I use a single equal signe "="?
(Feb-05-2020, 08:03 PM)el_bueno Wrote: [ -> ]here if num%2==0 why cant I use a single equal signe "="?

You already have two answers from two people to that exact question. The better question is "why do you think you should be able to use a single '='?" Why do you?
Maybe, but I reaaly need to make sure I did understand the difference between the two, so when I'll code Iwont stumble and think why do we choose that over the other.
Think of it this way, you are learning a foreign language and in this new language the word for equal is == and the word for assignment is = and that is it. Just as equals and assignment are not related in English neither are == and = in Python. They are two completely different concepts in both languages.
Some facts, that not many people knows:

for i in range(100):
#   ^ assignment to name i
    pass
with open('some_file.txt') as fd:
#                             ^^ assignment to name fd
    pass
[x for x in range(100)]
#      ^ assignment to name x
def foo(a, b):
#   ^^^ assignment of the function to the name foo
#       ^ assignment to name a
#          ^ assignment to name b
    pass
class Foo:
#     ^^^ assignment of class to name Foo
    pass
What we call variables, are just names. We assign an object (lives somewhere in memory) to a name.
Thank you so much, guys.

it really help me .

@jim2007 yes its a new language. I've learnt 4 languages and yes in the beginning we tend to think with the learnt language and try to apply its grammar to the new language, thats what I was doing.