How to Use a Boolean in Python? (With Examples)

July 29th, 2024
How to Use a Boolean in Python? (With Examples)

Boolean is just another data type similar to integers and strings. However, Boolean variables can have only two values: True and False. When you assign True or False to a variable, Python will treat it as if it belongs to the Boolean data type. The most common use of Boolean comes from Boolean expressions. These are statements that can be either true or false.

For example, 5 < 6 is a boolean expression. As a Python programmer, knowing about Booleans is very important as they are often used in conditional statements, loops, and logical expressions to control the flow of code execution.

In this article, we’ll be discussing the various ways in which booleans are used in Python.

Deploy and scale your Python projects effortlessly on Cherry Servers' robust and cost-effective dedicated or virtual servers. Benefit from an open cloud ecosystem with seamless API & integrations and a Python library.

How to assign Boolean values to Python variables

In Python, you can either directly assign True or False to a variable or you could use a boolean expression to assign a boolean value to a variable. See the examples below.

is_student  =  True
has_graduated  =  False

print(is_student)
print(has_graduated)

Output:

output of boolean variables

In the example above, we directly assign a Boolean value to a variable. Moreover, you can also assign the result of a boolean expression to a variable. Look at the example below.

age  =  20
is_adult  =  age  >=  18

print(is_adult)

Output:

output of boolean variable with is_adult condition

In this example, the result of the boolean expression "age >= 18" is assigned to the is_adult variable. Since 20 is greater than or equal to 18, the value of is_adult is True.

There is usually little value in directly assigning True or False to a variable. Most often, we use booleans through boolean expressions. Understanding how to use booleans in Python can be mainly divided into two parts. The first one involves creating proper boolean expressions for your needs. Python offers several methods for generating these expressions. The second part is about understanding how to effectively use boolean expressions in major programming components such as conditional statements, loops, and functions.

Let's start with creating boolean expressions.

Creating Boolean expressions

Boolean expressions in Python are primarily created using comparison operators and logical operators.

Comparison operators

Comparison operators compare two values and determine the relation between them. Here are the common comparison operators in Python.

  • "==" : Equal to

  • "!=" : Not equal to

  • ">" : Greater than

  • "<" : Less than

  • ">=" : Greater than or equal to

  • "<=" : Less than or equal to

These operators are used to build expressions that compare values, returning a boolean result.

For example, using the "==" operator checks if two values are equal.

a  =  5
b  =  5

result  =  a  ==  b

print(f"The result is {result}. This is because {a} and {b} are equal.")

Output:

output of checking if two variables are equal

These operators enable more complex boolean expressions by combining simpler ones. The result is True because a and b are equal.

Let's try another example using ">" to check if one value is greater than another.

age  =  18
is_adult  =  age  >=  18

print(f"The person is an adult: {is_adult}")

Output:
output of checking if the person is an adult

These examples show how the comparison operators form the basis of boolean expressions by evaluating the relationship between values.

Logical operators

Logical operators allow you to combine or modify boolean expressions. The primary logical operators in Python are as follows.

  • "and" : True if both operands are true

  • "or" : True if at least one of the operands is true

  • "not" : Inverts the boolean value of the operand

For the first example, let's combine a couple of conditions using the "and" operator.

high_score  =  90
good_behavior  =  True
honor_roll  =  high_score  >  85  and  good_behavior

print(honor_roll)

Output:

output of honor roll condition

Here, "honor_roll" is "True" because "high_score" is greater than 85 and "good_behavior" is "True".

Let’s see how the "or" operator can be used to check multiple conditions.

rain  =  False
umbrella  =  True
stay_dry  =  rain  or  umbrella

print(stay_dry)

Output:

output of stay dry condition

In this case, "stay_dry" is "True" because, even though it’s not raining (rain is False), having an umbrella (umbrella is True) ensures the "stay_dry" variable is "True".

Finally, Let’s see how the third logical operator "not" works.

is_minor  =  17
is_not_adult  =  not (is_minor  >=  18)

print(is_not_adult)

Output:

output of condition to check if not adult

In this case, the "is_not_adult" condition is "True" because is_minor is less than 18. The not operator inverts the boolean value of the expression "is_minor >= 18", turning False into True because the individual is indeed a minor and not an adult. This demonstrates how not can be effectively used to negate or invert a condition's outcome in Boolean logic.

Using boolean expressions in conditional statements

In Python, the main option for writing conditional statements is to use if-else statements. These if-else statements execute different code blocks based on certain conditions. We can use boolean expressions to specify these conditions.

As the code runs, these expressions will be evaluated to be either True or False, guiding the conditional statement to either execute the associated block of code or skip it.

For instance, look at how an "if" statement is used to check if a number is positive.

number  =  10
if  number  >  0:
    print("The number is positive.")

In this example, "number > 0" is the boolean expression. The if statement evaluates this expression, and since 10 is indeed greater than 0, the Boolean expression returns "True". Therefore, the print statement will be executed.

Output:

output of condition to check if number is greater than 0

You can get more specific with the parameters by adding multiple conditions to your code. This creates a more complex logic to give you a more refined output.

By adding multiple conditions to your code, you can get a more specific output. For example, let’s say that you wanted to check if a number is positive and also an even number, the code for that would look something like this

number  =  10
if  number  >  0  and  number  %  2  ==  0:
    print("The number is positive and even.")

Here, we've combined two conditions using the "and" logical operators: "number > 0 and number % 2 == 0". The entire expression must be "True" for the if statement to trigger. The "%" operator calculates the remainder of the number divided by 2, and if that’s 0, the number is even. So in this case, because 10 is positive and even, the message is printed.

Output:

output of condition to check if number positive and even

Using boolean expressions in loops

We use loops in Python to repeatedly execute a block of code. Very often, we use loops over a set of elements like integer numbers or a set of user-given inputs. In such cases, we encounter situations where we may need to run a different block of code, skip one iteration, or terminate the whole loop once a certain condition is met. To specify these conditions, we can use boolean expressions.

The way we use boolean expressions in loops can vary slightly depending on whether it's a while loop or a for loop. Therefore, let's consider each case separately.

Boolean expressions in "while" loops

"while" loops utilize boolean expressions to repeatedly execute a block of code as long as the given function is satisfied. The loop continuously checks whether the conditions have been fulfilled or not as it completes each iteration. Once the condition has been met, the program will exit the loop as it has fulfilled its purpose.

Here’s how you can use a boolean expression in a "while" loop.

number  =  0
while  number  <  5:
    print(f"Number is {number}")
    number  +=  1

In this example, "number < 5" is the boolean expression controlling the loop. The loop keeps running as long as this expression evaluates to True. Once the number reaches 5, the expression evaluates to False, ending the loop.

Output:

output of boolean expression in a while loop

Boolean expressions in "for" loops

While "for" loops in Python typically iterate over a sequence or iterator, boolean expressions can be used within the loop to decide whether to continue or terminate the loop prematurely using the "break" keyword or to skip to the next iteration using the "continue" keyword.

Here’s an example using a for loop and a boolean expression with the "break" statement.

elements  = [1, 2, 3, 4, 5]
for  element  in  elements:
    if  element  ==  3:
        break
    print(f"Element is {element}")

In this code, the "if" statement contains a boolean expression "element == 3". Which, when True triggers a "break", exiting the loop early.

Output:

output of boolean expression in an if condition

Also read: How to Reverse a List in Python

Using Boolean in Python functions

There are mainly two ways to use Boolean in Python functions. The first option is to use Boolean values as parameters for functions and the second option is to use them as return values from functions.

Using Boolean expressions as function parameters

You can pass Boolean expressions as arguments to functions. This allows the function to receive a "True" or "False" value, representing a condition outside the function. Here’s an example.

def  process_data(is_valid):
    if  is_valid:
        print("Data is valid, processing...")
    else:
        print("Data is invalid, skipping...")

data_check  =  10  >  5
process_data(data_check)

In this example, "process_data" takes a boolean parameter "is_valid". We then pass a boolean expression "10 > 5", which evaluates to "True", as an argument to this function. Inside the function, the parameter is used in a conditional statement to decide the flow of execution.

Output:

output of boolean expression as argument

Returning Boolean Values from Functions

Functions can also return boolean values. This is particularly useful for functions that perform checks or validations. The function performs its logic and then returns either True or False based on the outcome.

def  is_even(number):
    return  number  %  2  ==  0

number_check  =  is_even(42)
print(number_check)

In this "is_even" function, the boolean expression "number % 2 == 0" evaluates whether the number is even. If it is, the expression is True, and that’s what the function returns.

Output:

Output of boolean values from functions

Conclusion

You now know how to use boolean expressions in Python by using them in loops, controlling for loops, function parameters, and the overall basics. Although these are the very basics, by properly going through it you’ll be well on your way to being an expert in using boolean expressions in Python. To add to this knowledge, look for more complex functions of these boolean expressions in Python and practice with real-world examples. Happy learning and happy coding!

If you found this guide helpful, look at our guide on how to manage conda environments and how to install Anaconda on Ubuntu 22.04.

Shanika is a technical consultant and writer with over eight years of experience as a software engineer in the IT sector. Her professional journey started as a software engineer with WSO2. At the same time, she started working as a freelancer on Upwork. She has collaborated with numerous companies throughout her freelance career, including Digication, Splunk, BMC.com, Filestack, APILayer, Flosum, Blazemeter, Sencha, and over twenty others. Having opportunities to work with various companies in different roles has allowed her to amass a wealth of experience. Shanika is an expert in web development, programming, Java, Python, React, Cypress, CI/CD, Docker, and Kubernetes,m. She has significantly contributed to developing products such as IAM solutions, APIs, OCR technologies, test management systems, and front-end frameworks throughout her career. She has also produced blog articles, tutorials, user guides, product documentation, and many other documents, as well as consulting companies to enhance their productivity. Overall, Shanika brings together the experience of a web developer, automation engineer, DevOps developer, software consultant, and technical writer, which is the main reason behind her success as a freelancer. Shanika received her B.Sc. (Hons) in Computer Science from University of Moratuwa, Sri Lanka and resides in Colombo, Sri Lanka.

Start Building Now

Deploy your new Cloud VPS server in 5 minutes starting from $5.83 / month.

We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: b0376f5bd.760