Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 221
Phoenix Holmes Avatar asked Jun 09 '26 23:06

Phoenix Holmes


1 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.

like image 92
Paulo Scardine Avatar answered Jun 11 '26 23:06

Paulo Scardine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!