How does Python represent TRUE and FALSE?
Say you want to define a function that returns TRUE or FALSE. For example, you need a function that acts like a flip of a weighted coin. The function coin(prob) (it's not built-in -- you have to define it) accepts a probability (0.0<=prob<=1.0) and returns true with probability prob and false with probability 1-prob. When you define the function, what gets returned?
Python represents FALSE with a zero, and true with any other number, generally 1. So see this, try this:
if 1: print "It was true." else: print "No, it was false."Or try this:
if 0: print "It was true." else: print "No, it was false."
So, you can put a 1 (or any nonzero number) or a 0 wherever Python expects something that is TRUE or FALSE. That means your boolean function can just return a 1 or a 0:
def coin(prob):
if random.random() < prob:
return 1
else:
return 0
if coin(0.5):
print "HEADS"
else:
print "TAILS"
It works the other way, too: you can use a built-in boolean function to return a 1 or a zero: try writing print(4<2). You can use this in clever ways. For one thing, you can shorten coin(prob):
def coin(prob):
return (random.random() < prob)
Or, try predicting the behavior of this code:
num_donuts = input("How many donuts did you eat?" )
print "You ate", num_donuts, "donut" + (num_donuts > 1)*"s" + "."
