Understanding the False
Keyword in Python
How to Use False in Python
Using False in the Python programming language is straightforward. You can assign False to a variable or get it as a result of comparison or logical operators.
is_negative = 100 < 0
When to Use False in Python
Conditional Statements
Such execution paths often exist in user authentication, feature toggling, or error-checking scenarios.
if feature_enabled:
print("Feature is enabled.")
else:
print("Feature is disabled.") # This line executes
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 False if the evaluated condition doesn't meet the criteria set by the comparison operator.
For example, in a benefit-check scenario, you might compare the age of a user with a certain threshold age.
# 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 counter > 0:
print(counter)
counter -= 1 # Eventually, counter becomes 0, making the condition False
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
Examples of False in Python
while user_input == "":
user_input = input("Enter a non-empty string: ")
if user_input == "":
print("Invalid input. Please try again.") # Executes if user_input is False (empty)
if b == 0:
return False # Indicates division by zero is not allowed
return a / b
result = divide(10, 0)
if not result:
print("Division by zero!") # This line executes
if number <= 1:
return False # Numbers less than or equal to 1 are not prime
for i in range(2, number):
if number % i == 0:
return False # Number is divisible by a number other than 1 and itself
return True
print(is_prime(4)) # Output: False
Learn More About False in Python
is_inactive = not is_active # Converts True to False
Besides the explicit False keyword, several other values are evaluated as False within conditional statements or logical operations. Values that evaluate to False are called "falsy." Here are some common examples of falsy values:
- 1. Any numeric type with a value of zero, such as 0, 0.0, or 0j (complex number)
- 2. Empty instances of sequences and collections, including empty strings (''), lists ([]), tuples (()), dictionaries ({}), and sets (set())
- 3. The None object, which denotes the absence of a value or a null value in Python.
Falsy values allow for concise and expressive conditional checks. Instead of checking if a list is empty by comparing its length to 0, you can also use the list itself:
if not my_list: # This evaluates to True because an empty list is falsy print("The list is empty.")
Similarly, consider checking if a variable has a non-null value. You can simply use the variable in the condition:
if not my_var: # This evaluates to True because None is falsy print("my_var has not been set.")
While using falsy values can make your code more concise, it might also lead to unintended consequences. For example, a function that returns 0 (falsy) will evaluate to False in a conditional check. In such cases, it's important to use more explicit checks to avoid mistakes:
# Imagine this function calculates a discount and can return 0 if no discount is applicable
return 0
discount = calculate_discount(["apple", "banana"])
if not discount: # This might be misleading as a 0 discount is a valid response but is treated as False
print("No discount applied.")
In this case, an explicit comparison to 0 would be clearer:
print("No discount applied.")
The bool() Function
Python’s built-in bool() function converts a non-boolean value to a boolean value: True or False. bool() takes a single argument and returns False for falsy values and True for truthy values.
Consider the following examples:
print(bool(0)) # Output: False
print(bool('')) # Output: False
print(bool(None)) # Output: False
# Truthy values
print(bool(1)) # Output: True
print(bool('Hello')) # Output: True
print(bool([1, 2, 3])) # Output: True
The bool() function can be helpful to ensure a certain value evaluates to a boolean value. This can be particularly useful in conditional statements, function returns, and data validation.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.