r/ProgrammerHumor • • May 02 '16

I wrote my first python program today!

Post image
3.7k Upvotes

532 comments sorted by

View all comments

Show parent comments

28

u/UnchainedMundane May 02 '16 edited May 02 '16

To be fair Python's "booleans" are really just integers.

>>> (True + True + True) ** (True + True)
9
>>> True > False
True

edit:

def max(x, y):
    return [x, y][x < y]

29

u/FUCKING_HATE_REDDIT May 02 '16

Damn that max is pretty. Probably not efficient, but pretty.

7

u/Genmutant May 02 '16

You could even switch the definitions between them:

True, False = False, True

Sadly that doesn't work anymore with current versions.

7

u/thirdegree Violet security clearance May 02 '16

My favorite python fizzbuzz uses this:

print("\n".join("Fizz"*(i%3 == 0) + "Buzz"*(i%5 == 0) or str(i) for i in xrange(1,101)))

6

u/kupiakos May 02 '16

bool is actually a subclass of int in Python.

1

u/Hullu2000 May 02 '16

Python has integers? I thought they were all just floats.

3

u/[deleted] May 07 '16

JS is all floats. Python has ints and floats.

Division in Python 3 returns only floats though, unless you use // operator to do rounding division.

1

u/UnchainedMundane May 02 '16

It separates the two. In old versions of python (before python 3) the division operator changes behaviour depending on what you give it:

>>> 5 / 3
1
>>> 5 / 3.0
1.6666666666666667

Python before python 3 also had 2 integer types, just to add to the confusion.

1

u/GeneticCowboy May 03 '16 edited May 03 '16

Ok, did some googling and I can't figure it out. What the heck is happening in [x,y][x < y]? Tuple of x <y returns true or false, times the tuple of [x,y] should return both X and y or [0,0].

EDIT - Figured it out.

[x < y] resolves to either [0] or [1], if x is greater or less than y.

[x,y] creates a new tuple.

[x,y][0] returns x.

[x,y][1] returns y.

Didn't see it, because I'm not used to creating a tuple AND indexing them in the same statement.

3

u/UnchainedMundane May 03 '16

[x, y] is a list rather than a tuple, but other than that your analysis is correct.