True or false output based on a probability

Mike Vella picture Mike Vella · May 4, 2011 · Viewed 32.7k times · Source

Is there a standard function for Python which outputs True or False probabilistically based on the input of a random number from 0 to 1?

example of what I mean:

def decision(probability):
    ...code goes here...
    return ...True or False...

the above example if given an input of, say, 0.7 will return True with a 70% probability and false with a 30% probability

Answer

NPE picture NPE · May 4, 2011
import random

def decision(probability):
    return random.random() < probability