How do if and elif work behind the scenes

How do if and elif work behind the scenes

when we use if or elif we say:

x = 1
if x == 1:
  print('x is 1')
elif x == 2:
  print('x is 2')

Instead of == why cant we just use = to check for assignment instead.

Answer

This behavior is inherited from C. In C, the = operator is just like any other operator. An assignment statement is not special, so it is legal to say, for example:

    if( (x = y) > 9 )

which assigns y to x then tests its value. Because of that, it was necessary to use a different symbol for the "equals" comparison. They chose "==", and most programming languages since then have followed suit.

Also consider the following valid Python code:

   isequal = x == y

which assigns a boolean value. I think you can see it is necessary to use a different symbol.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles