Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do "and" and "or" work when combined in one statement?

For some reason this function confused me:

def protocol(port):
    return port == "443" and "https://" or "http://"

Can somebody explain the order of what's happening behind the scenes to make this work the way it does.

I understood it as this until I tried it:

Either A)

def protocol(port):
    if port == "443":
        if bool("https://"):
            return True
    elif bool("http://"):
        return True
    return False

Or B)

def protocol(port):
    if port == "443":
        return True + "https://"
    else:
        return True + "http://"

Is this some sort of special case in Python, or am I completely misunderstanding how statements work?

like image 856
orokusaki Avatar asked Apr 05 '10 17:04

orokusaki


2 Answers

It's an old-ish idiom; inserting parentheses to show priority,

(port == "443" and "https://") or "http://"

x and y returns y if x is truish, x if x is falsish; a or b, vice versa, returns a if it's truish, otherwise b.

So if port == "443" is true, this returns the RHS of the and, i.e., "https://". Otherwise, the and is false, so the or gets into play and returns `"http://", its RHS.

In modern Python, a better way to do translate this old-ish idiom is:

"https://" if port == "443" else "http://"
like image 90
Alex Martelli Avatar answered Nov 15 '22 18:11

Alex Martelli


and returns the right operand if the left is true. or returns the right operand if the left is false. Otherwise they both return the left operand. They are said to coalesce.

like image 26
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 18:11

Ignacio Vazquez-Abrams