In Python, Booleans express truth values: True or False. When you compare two values, Python produces one of these two results, and that outcome determines what action your script should take next.
Find out when Booleans appear in Python code and how they help control the flow of your program.

Prerequsites
- Python 3 installed (check your Python version).
- Access to a text editor or IDE.
- A way to run the code (in the terminal or in an IDE).
Python Boolean Data Type
Python developers work with several data types, including strings, integers, floats, lists, and Booleans. Booleans are unique because they can only be one of two values: True or False.
The Boolean data type is used frequently because much of programming logic boils down to a simple yes-or-no decision. Scripts rely on Booleans to:
- Validate user input.
- Trigger the following action in a workflow.
- Provide feedback to users.
- Enforce rules.
- Toggle features on and off.
You can assign Booleans manually when you already know the intended state, such as defining default settings or configuration flags:
test_mode = True
fraud_check_enabled = False
However, manual assignments are rare in practice. Most Boolean values in Python come from conditional expressions. These expressions compare values, and Python evaluates them to determine whether the result is true or false.
Note: Python includes simple built-in methods for creating, opening, and closing files. Learn more about basic file handling in Python.
A common example is validating user input, like checking if a password is correct:
stored_password = Passwd123
entered_password = paswd12
is_correct_password = entered_password == stored_password #False
In this example:
entered_password == stored_passwordis a comparison expression.- Python evaluates the expression and returns either
TrueorFalse. - In this case, it returns
Falsebecause the user entered the wrong password.
You can now use the result to control what the script does next:
if is_correct_password
print("Welcome!")
else:
print("The password is incorrect. Try again!")
If the password is correct, the user gains access and sees the Welcome! message. If the password is incorrect, they will see The password is incorrect. Try again! error instead.
Note: Comments in Python are a good practice, and you will see them throughout the code examples in this guide. Python ignores comments, and they exist only to explain what the code does.
Developers often need to validate more than one rule. For example, checking if the password is correct and if the minimum length criteria are met:
entered_password = "paswd12"
is_correct_password = entered_password == stored_password #False
is_long_enough = len(entered_password) >= 8 #False
if is_correct_password: #False
print("Welcome!")
elif not is_long_enough: #True
print("Password too short.")
else:
print("The password is incorrect. Try again!")
Python evaluates each condition and produces a Boolean result. The results determine which branch of the conditional statement executes and drives the program's decisions.
Boolean Operators
Python includes several categories of operators, but two of them matter the most when working with Booleans: comparison operators and logical operators.
Together, they cover most Boolean logic in Python. They enable code to respond to actual situations, such as authenticating users or handling API responses.
Comparison Operators
Python uses comparison operators to check the relationship between two values and return a True or False result. Comparison operators include:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 2 == 2 | True |
!= | Not equal to | 5 != 7 | True |
> | Greater than | 2 > 9 | False |
< | Less than | 6 < 4 | False |
>= | Greater than or equal to | 10 >= 10 | True |
<= | Less than or equal to | 4 <= 6 | True |
In this example, the == and < operators compare the risk level of an approved transaction with predetermined risk thresholds:
payment_status = "APPROVED"
is_approved = payment_status == "APPROVED" # True
risk_score = 42
is_low_risk = risk_score < 50 # True
The payment is considered low risk because both conditions evaluate to True.
Logical Operators
Logical operators take the values produced by comparison operators and combine them into more complex conditions. Logical operators include:
| Operator | Meaning |
|---|---|
and | Returns True only if both conditions are true. |
or | Returns True if at least one condition is true. |
not | Reverses the result and returns False if the result is true, and vice versa. |
In the following example, Python checks:
- If the payment is successful.
- Whether the risk score is below the required threshold.
- If a 3D Secure check is required.
response = {
"success": True,
"threeDSRequired": False,
"riskScore": 22
}
is_successful = response["success"] #True
requires_3ds = response["threeDSRequired"] #False
is_safe = response["riskScore"] < 40 #True
if : is_successful and is_safe and not requires_3ds #True
print("Payment approved and processed.")
else:
print("Additional checks needed or payment failed.")
Because all parts of the is_successful and is_safe and not requires_3ds expression evaluates to True, the system prints Payment approved and processed.
Python Boolean Testing
Boolean testing in Python refers to evaluating expressions that result in a True or False result. Tests are typically used to compare values, filter data, validate input, and control program flow.
The examples in this guide are presented from the Ubuntu command line, but the same code will work in any Python editor or IDE.
Testing Numeric Relations
You can use comparison operators to test sizes, limits, and thresholds. For example, to check if a transaction amount exceeds or falls below a predefined daily limit:
1. Access the command line and use a text editor, such as nano, to create a .py file:
nano numeric_test.py
2. Paste the following code into the file, then save and close it:
amount = 120.00
daily_limit = 100.00
is_above_limit = amount > daily_limit
is_within_limit = amount <= daily_limit
print(is_above_limit) # True
print(is_within_limit) # False
if is_above_limit:
print("Transaction exceeds the daily limit. Flag for review.")
else:
print("Approved.")
3. Run the script in the terminal:
python3 numeric_test.py
4. Python evaluates the amount > daily_limit and the amount <= daily_limit comparison expressions and returns a Boolean result for each.

5. Since amount > daily_limit evaluates to True, Python also executes the first branch of the if statement and prints:
Transaction exceeds the daily limit. Flag for review.
If the amount were below the limit, the script would print Approved.
Testing Equality and Inequality
You can use the == operator to check if two values are equal, and the != operator to check if they differ. These operators are often used to compare strings, validate user input, or control access, like in the following example:
1. Create a .py file using a text editor:
nano equality_test.py
2. Paste the following code, and save the file:
role = "admin"
print(role == "admin") #True
print(role != "guest") #True
print(role == "user") #False
if role == "admin":
print("Welcome, admin!")
else:
print("Access denied.")
3. Execute the script from the terminal:
python3 equality_test.py
4. Python evaluates each comparison expression and prints the results.
role == "admin"- Truerole != "guest"- Truerole == "user"- False
5. Because the role == "admin" condition evaluates to True, Python executes the first branch of the if statement:
Welcome, admin!

Note: When working with numeric data stored as text, you may need to convert those strings into floats. Learn the different methods for converting strings to floats in Python.
Testing Object Identity
Unlike comparison operators, the is operator does not compare values. It checks whether two variables refer to the same object in memory.
One common use of the is operator is object identity testing. For example, to confirm if a value is None when a user lookup fails:
1. Create a test .py file in the terminal:
nano identity_test.py
2. Paste the following code:
user = None
print(user is None) #True
print(user is not None) #False
if user is None:
print("User not found.")
else:
print("User exists.")
3. Run the script from the terminal:
python3 identity_test.py
4. Python evaluates the user is None condition, and since it is True, it executes the first branch:
User not found.

Note: Using is None is preferred over comparison operators (== None) because it is faster, cleaner, and follows Python best practices.
Logical Condition Testing
Logical operators (and, or, and not) enable developers to combine Boolean expressions into more complex conditions. To test a logical condition:
1. Create a .py file for the test:
nano logical_test.py
2. Paste the following Python code. This example initiates a 3DS check only when a transaction is domestic (US) and high-value:
amount = 75.00
currency = "USD"
card_country = "US"
is_high_value = amount > 50
is_domestic = card_country == "US"
print(is_high_value) # True
print(is_domestic) # True
should_require_3ds = is_high_value and is_domestic
print(should_require_3ds) # True
# Using the combined condition in a real decision
if should_require_3ds:
print("3DS verification required.")
else:
print("Standard authorization.")
3. Run the script:
python3 logical_test.py
4. Python evaluates the amount > 50 and card_country == "US" comparison expressions.
5. Since both subconditions are True, it evaluates the logical expression is_high_value and is_domestic. The combined result is also True.
6. Python then checks the value of the should_require_3ds, and because it is True, Python executes the first branch:
3DS verification required.

If either subcondition were False, the final output would be Standard authorization.
The bool() Function and Truthiness Testing
Python treats some values as True or False even though they are not literal Boolean values. This is called truthiness. By wrapping a value in a bool() function, you can determine if Python will treat a condition as True or False:
1. Create a .py test file:
nano bool_test.py
2. Enter the following code to check for optional fields using the bool() function:
customer_email = ""
metadata = {}
print(bool(customer_email)) # False
print(bool(metadata)) # False
if not bool(customer_email):
print("Customer email is missing. Cannot send receipt.")
if not bool(metadata):
print("No additional payment metadata provided.")
3. Run the script:
python3 bool_test.py
4. Python confirms that bool("") and bool({}) are False, and prints:
Customer email is missing. Cannot send receipt.
No additional payment metadata provided.

Truthiness Testing
Usually, developers rely on Python's automatic truthiness rules rather than explicitly calling bool(). The following values are considered False when tested in an if statement:
| Value | Meaning |
|---|---|
0 | Zero integer |
0.0 | Zero float |
"" | Empty string |
[] | Empty list |
{} | Empty dictionary |
() | Empty tuple |
None | No value/null |
False | Literal Boolean |
All other values are considered True.
Because empty strings, containers, and the number 0, None, and False all evaluate to False, truthiness checks are very common for testing empty lists or missing fields. For example, the following code checks if the errors list has content:
errors = []
if not errors:
print("No validation errors. Proceed with payment.")

Since errors is an empty list, not errors evaluates to True, and the corresponding message is printed.
Short-Circuit Behavior
Python uses a process called short-circuiting to evaluate logical expressions:
- For the expression
x and y, Python stops early ifxisFalse. - For the expression
x or y, Python stops early ifxisTrue.
This process saves time by skipping expressions that do not need to be evaluated. To test short-circuit behaviour in Python:
1. Create a .py file:
nano short_circuit_test.py
2. In this example, the system checks if a user object exists and if it is active. Python stops evaluating the expression as soon as the outcome is known:
user = None
if user is not None and user.is_active:
print("Welcome!")
else:
print("Redirect to login.")
# OR example
logged_in = False
has_temp_access = True
if logged_in or has_temp_access:
print("Temporary access granted.")
else:
print("Access denied.")
3. Run the script:
python3 short_circuit_test.py
4. Python evaluates the first part of the condition:
user is not None
Since the user is None, the expression is False.
5. As a result, Python stops and does not evaluate user.is_active. Instead, Python executes the else branch:
Redirect to login.
6. In the or example, Python evaluates logged_in or has_temp_access. Because logged_in is False, Python checks the second value.
7. has_temp_access is True, forcing Python to stop early and print:
Temporary access granted.

Using Booleans in Control Flow
As shown in previous examples, Python uses Boolean results to decide which block of code to execute next or whether a loop should continue iterating. This process is known as control-flow testing.
The statements that depend on Boolean testing include:
ifelifelsewhile
Note: The for loop is also part of Python's control flow, but does not rely on Boolean testing.
To test how Booleans control program flow:
1. Open a terminal and create a .py file:
nano control_flow_test.py
2. Paste the following code. This example validates an email string and limits login attempts:
# Email validation example
email = "[email protected]"
if "@" in email and "." in email.split("@")[-1]:
print("Email looks valid.")
else:
print("Invalid email format.")
# Limiting login attempts
attempts = 0
max_attempts = 3
while attempts < max_attempts:
print(f"Attempt {attempts + 1}: Prompting for password...")
attempts += 1
print("Maximum attempts reached.")
3. Execute the script:
python3 control_flow_test.py
4. Python evaluates the two membership tests in the if expression:
if "@" in email and "." in email.split("@")[-1]
Both must be True for the combined condition to be True.
5. Based on the results, Python executes the correct branch:
Email looks valid.
If either condition were False, Python would run the else block:
Invalid email format.
6. Python now evaluates the loop condition:
attempts < max_attempts
7. Since attempts starts at 0, the condition is True and Python enters the loop.

Each iteration displays a prompt, increments the attempts value, and repeats the process until the condition becomes False.
Boolean Testing with Functions
Developers can wrap Boolean checks in a function rather than scattering them throughout the code. As a result, the code is cleaner and can be packaged into reusable components.
To see how Booleans work within functions:
1. Open a terminal and create a test .py file:
nano function_boolean_test.py
2. Paste the following code. The function in this example validates transactions based on the amount and the card issuing country:
def is_transaction_valid(amount, card_country, allowed_countries):
return amount > 0 and card_country in allowed_countries
allowed = ["US", "CA", "UK"]
print(is_transaction_valid(50, "US", allowed)) # True
print(is_transaction_valid(-10, "US", allowed)) # False
print(is_transaction_valid(30, "FR", allowed)) # False
if is_transaction_valid(50, "US", allowed):
print("Transaction allowed.")
else:
print("Transaction rejected.")
3. Run the script in the terminal:
python3 function_boolean_test.py
4. Python evaluates the following:
50 > 0and"US" in allowedisTrue-10 > 0isFalse"FR" in allowedisFalse
5. Because the if is_transaction_valid(50, "US", allowed):function returns True, Python executes he first branch:
Transaction allowed.

If the validation failed, Python would execute Transaction rejected.
Conclusion
This guide showed you how Booleans in Python work and how to use them to build decisions into your code.
Next, learn about Python dictionaries, another data type that pairs well with Booleans and is ideal for validating user data and looking up key-value pairs.



