• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python Random Boolean – How to Generate Random Boolean Values

Python Random Boolean – How to Generate Random Boolean Values

February 10, 2022 Leave a Comment

In Python, we can easily get a random boolean using the Python random() or choice() function from the random module.

import random import choice, random

#Using random.random() 
random_bool_with_random = True if random() > 0.5 else False

#Using random.choice()
random_bool_with_choice = choice([True, False])

print(random_bool_with_random)
print(random_bool_with_choice)

#Output:
True
False

Being able to generate random numbers efficiently when working with a programming language is very important. In Python, we can generate random number easily to get random boolean values.

To get a boolean randomly, we can use the Python random module. In the Python random module, we can use the Python random() function, or Python choice() function.

The random() function generates a random float between 0 and 1. The Python choice() function takes in a list of choices and gives a random selection from those choices.

Below is an example of how to get a boolean values randomly in Python.

import random import choice, random

#Using random.random() 
random_bool_with_random = True if random() > 0.5 else False

#Using random.choice()
random_bool_with_choice = choice([True, False])

print(random_bool_with_random)
print(random_bool_with_choice)

#Output:
True
False

One such application of generating random boolean values would be if you wanted to generate a coin flip in Python.

Below is some sample code of how you could flip a coin in Python using the random module.

from random import choice, random

#Using random.choice()
coin_flip_with_choice = choice(["Heads","Tails"])

#Using random.random() 
coin_flip_with_random = "Heads" if random() > 0.5 else "Tails"


print(coin_flip_with_choice)
print(coin_flip_with_random)

#Output:
Tails
Heads

Using Python to Generate a List of Random Booleans in a Loop

If you want to generate a list of random booleans, we can easily define a function and use a loop in Python.

In this example, we will create a function which takes one argument, the number of booleans you want to create, and will return a list of random booleans.

Below is some sample code which will get the random booleans for you in Python.

from random import random

def rand_bools(n):
    bools = []
    for x in range(0,n):
        bools.append(True if random() > 0.5 else False)
    return bools

print(rand_bools(10))

#Output:
[True, True, True, True, True, False, True, True, True, False]

Generating a Random Boolean With Probability

In the examples above, we’ve been assuming that we want to have 50% True and 50% False generated from our Python program.

If we want to creat a random boolean based on a probability, we can use the random() function and adjust the threshold.

For example, if we want to generate True 70% of the time, then we would do the following in Python:

import random import choice, random

#Using random.random() 
random_bool_with_random = True if random() > 0.7 else False

Generating Random Booleans with numpy and pandas in Python

If you are using numpy or pandas, we can fill a column with random boolean values using the numpy random.rand() allows us to generate random numbers in the same way as the Python random module.

Below is some code which will allow you to get boolean values randomly in Python with numpy.

import pandas as pd
import numpy as np

coin_flip_series = pd.Series(np.random.randint(2, size=10))

print(coin_flip_series)

#Output:
0    1
1    0
2    0
3    0
4    1
5    1
6    1
7    0
8    0
9    1
dtype: int32

Hopefully this article has been beneficial for you to learn how to get a random boolean in Python using the random module.

Other Articles You'll Also Like:

  • 1.  pandas variance – Compute Variance of Variables in DataFrame
  • 2.  How to Output XLSX File from Pandas to Remote Server Using Paramiko FTP
  • 3.  Python Split List into N Sublists
  • 4.  Get Current Datetime in Python
  • 5.  Add Key Value Pair to Dictionary in Python
  • 6.  Date Format YYYYMMDD in Python
  • 7.  pandas Drop Columns – Delete Columns from a DataFrame
  • 8.  Using Python to Remove Duplicates from List
  • 9.  Selenium minimize_window() Function to Minimize Window in Python
  • 10.  pandas covariance – Calculate Covariance Matrix Using cov() Function

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy