If you’re looking for a way to generate a random boolean value in Python, then this is the tutorial for you.
To generate a random boolean value, you need to make use of the random
module provided by Python.
The following examples show how you can use the methods in the random
module to generate a random boolean value.
1. Use random.getrandbits()
method
The random.getrandbits(x)
method generates a random int that has x
number of bits.
You can use this method and pass 1
as its argument so it generates a random number between 0
and 1
.
To get a random boolean value, convert the result with the bool()
function like this:
import random
random_val = bool(random.getrandbits(1))
print(random_val) # True or False
The random_val
will contain either True
or False
depending on the result of getrandbits()
.
2. Use random.randint()
method
The randint(x,y)
method is used to generate a random number between x
and y
.
To get a random boolean value, convert the result of randint()
with the bool()
function as follows:
import random
random_val = bool(random.randint(0,1))
print(random_val) # True or False
The random_val
variable will alternate between True
and False
depending the result returned by the randint()
method.
3. Use random.choice()
method
The random.choice()
method returns a randomly selected element from a list.
You can use this method and pass a list of boolean values as shown below:
import random
my_list = [True, False]
random_val = random.choice(my_list)
print(random_val) # True or False
The variable random_val
will get either True
or False
each time you run the code above.
4. Use random.choices()
method
If you want to generate a list of random boolean values, you can use the random.choices()
method and pass the named k
parameter.
The k
parameter will repeat the choice as many as k
times. Here’s the code:
import random
my_list = [True, False]
# Repeat 4 times
random_val = random.choices(my_list, k=4)
print(random_val)
# Repeat 7 times
random_val = random.choices(my_list, k=7)
print(random_val)
An example output could be:
[False, False, True, False]
[False, True, False, False, True, False, False]
You can adjust the k
parameter to fit your requirements.
Conclusion
The Python random module has four ways to generate random boolean values. Although they may have small differences in speed, there won’t be a big difference since modern computers can handle them all well.
These random methods may differ slightly in performance, but there won’t be a big difference since modern computers can handle them all well.
The getrandbits
, randint
, and choice
methods can all be used to generate a single random boolean value, while the choices()
method can be used to generate a list of random boolean values.
I hope this article is helpful. Happy coding! 🐍