Course

Python Booleans (True and False): Syntax, Usage, and Examples

In Python, booleans are a fundamental data type that represents truth values: True or False. Booleans enable decisions, comparisons, and the execution of specific code blocks based on conditions.

How to Use Booleans in Python

Using booleans in the Python programming language is straightforward. You can assign True or False to a variable or get them as a result of boolean expressions. For example, working with dictionaries or arrays, you might need to evaluate conditions using boolean values.

python
is_active = True # Direct assignment is_positive = -1 > 0 # Result of a comparison, evaluates to False

When to Use Booleans in Python

Booleans are essential when you need to make decisions based on whether something is true or false. Here are some common use cases:

Conditional Statements

The boolean data type is essential for conditional statements. Conditional statements allow you to execute blocks of code based on certain conditions.

If the condition of an if statement evaluates to True, the code block below if the if statement executes. If the condition is False, the block of code below else executes.

python
user_age = 20 if user_age >= 18: print("You are eligible to vote.") # This block executes if the condition is True else: print("You are not eligible to vote.")

Comparisons

Comparisons are a common type of boolean expression. By comparing two variables or values, you can check the relationship between them. The six comparison operators in Python are == (equality), != (inequality), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).

Comparisons return True if the evaluated condition meets the criteria set by the comparison operator. Otherwise, comparisons return False.

For example, in a benefit-check scenario, you might compare the age of a user with a certain threshold age.

python
age = 25 # Multiple comparisons combined with a logical operator if age >= 65: print("Eligible for senior benefits.") # This line won't execute because one comparison is False else: print("Not eligible for senior benefits.")

While Loops

In while loops, booleans are necessary, too. Booleans continue the loop while a condition evaluates to True and terminate the loop when the condition becomes False.

python
count = 0 while count < 5: print(count) count += 1 # This loop prints numbers from 0 to 4

Logical Operations

In Python, boolean values represent the truth of an expression. Logical operations with boolean operators allow you to combine, invert, or compare expressions. The three boolean operators in Python are and, or, and not.

python
a = True b = False result1 = a and b # False because both operands are not True result2 = a or b # True because one operand is True result3 = a and not b # True because a is True and b is not True

You can also use logical operations while working with tuples and dictionaries to filter data or manage conditions.

Examples of Booleans in Python

User Authentication

In web and application development, booleans can manage user authentication states. A common example might be determining if a user is logged in or has the appropriate permissions by returning a boolean variable.

python
is_logged_in = True if is_logged_in: print("Access granted.") else: print("Please log in.")

Data Validation

Booleans are crucial for validating input data, ensuring that it meets certain criteria before being processed or stored.

python
def is_valid_age(age): return 0 < age < 120 # Ensures age is within a reasonable range print(is_valid_age(25)) # Outputs: True

Feature Flags

In software development, booleans can enable or disable features during runtime. Such feature flags allow for easy management of feature rollouts and testing.

python
feature_enabled = False if feature_enabled: print("New feature is enabled.") else: print("New feature is currently disabled.")

Decision Making in Games

In game development, booleans can control game states. For example, a boolean might determine if a player has completed a level or if a game is paused.

python
level_complete = True if level_complete: print("Congratulations! Moving to the next level.")

You might also determine if a player has won a level by checking multiple conditions.

python
python CopyEdit level_complete = True bonus_earned = False if level_complete and not bonus_earned: print("You won the level but missed the bonus!")

Here, combining boolean logic and arithmetic operations ensures that both game progression and score calculations are accurate.

Handling Boolean Operations

Understanding boolean operators (and, or, not) is crucial for combining multiple boolean expressions into a single conditional statement.

python
has_high_score = True has_extra_lives = False if has_high_score and not has_extra_lives: print("High score, but no extra lives!")

Learn More About Python Booleans

Truthy and Falsy Values

In Python, values are referred to as “truthy” or “falsy” in boolean contexts. Most values are “truthy” except for a few “falsy” values like None, False, 0, 0.0, empty sequences ('', (), []), and empty mappings ({}).

python
if []: # An empty list is "falsy" print("Won't print") else: print("An empty list is considered False")

The bool() Function

The built-in bool() function converts a value to a boolean, returning True or False. bool() is particularly handy for testing the truthiness of an expression or variable.

python
print(bool(0)) # Outputs: False, because 0 is considered "Falsy" print(bool(42)) # Outputs: True, because non-zero numbers are "Truthy" print(bool("")) # Outputs: False, because an empty string is "Falsy"

Boolean Operators

Boolean operators, also called logical operators, allow you to construct more complex boolean expressions in Python. The three primary boolean operators are and, or, and not.

The and operator allows you to combine multiple conditions. and requires all conditions to be True for the entire expression to evaluate to True. This makes it particularly useful when a decision depends on the fulfillment of several criteria.

python
is_online = True has_subscription = True # Both variables need to be True can_access_content = is_online and has_subscription print(can_access_content) # Output: True

or requires only one of the conditions to be True for the entire expression to evaluate to True. This makes it useful in scenarios where there are multiple potential paths to achieve a certain outcome.

python
is_admin = False has_special_access = True # Only one variable needs to be True can_edit = is_admin or has_special_access print(can_edit) # Output: True

The not operator inverts the truth value of its operand. If a condition is True, adding not in front of it makes it False, and vice versa. This can be particularly helpful for readability, making conditions as clear as possible.

python
is_restricted = False # Inverts the boolean value can_proceed = not is_restricted print(can_proceed) # Output: True

Booleans in Function Returns

Functions often return booleans to indicate success, failure, or the state of an object. Such function returns provide a clear and simple way to communicate the outcome of a function.

python
def is_even(number): return number % 2 == 0 if is_even(4): print("Number is even.") else: print("Number is odd.")