generate a random boolean in python

There are several ways to generate a random boolean in Python, here are two easy options using the random module:

  1. Using randint:
main.py
import random

random_bool = bool(random.randint(0, 1))
print(random_bool)
75 chars
5 lines

The randint function generates a random integer between the two arguments (inclusive). We then use the bool() function to convert the integer to a boolean value, where 0 is False and 1 is True.

  1. Using choice:
main.py
import random

random_bool = random.choice([True, False])
print(random_bool)
77 chars
5 lines

The choice function randomly selects an element from a given sequence. We pass in the sequence [True, False] and it randomly selects either True or False.

gistlibby LogSnag