How do I read this python code? var1 = var2 == var3

Viewed 1615

I'm struggling to understand what this represents

var1 = var2 == var3

My guess would be that this is equivalent to:

if (var2 == var3):
     var1 = var2
4 Answers

The assignment var1 = var2 == var3 works more like this:

if var2 == var3:
    var1 = True
else:
    var1 = False

If you evaluate the expression var2 == var3 on the REPL you will get True or False depending on they comparing equal or not. In Python you can assign any expression to a variable so the resulting value would be assigned to var1 in your example.

In Python a == b is an expression but the assignment a = b is a statement. In many languages both are expressions - for example in Javascript you are allowed to do (although not very good style):

a == (b = c)

In Python it is not allowed (SyntaxError):

a == (b = c)

The controverse PEP 572 introduces the new assignment operator := that is an expression.

Equality operator == has precedence over = assignment. So this equates to:

var1 = (var2 == var3)  # Boolean

The == operator itself will return either True or False; it is this value that is assigned.

var1 = var2 == var3

Means:

  1. create a variable called var1

  2. Assign it to the True False Boolean which is var2 equals to var3 (using the == operator)

Here's an example:

>>> var2=1
>>> var3=1
>>> var2==var3
True
>>> var1 = var2==var3
>>> var1
True
>>> 

Your assumption is incorrect. The code you posted would be this:

var2 = 1
var3 = 1

var1 = var2 == var3

#var1 is true because var2 and var3 are equal 
Related