How to Check If a Value Is Falsy in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to identify falsy values in Python. Understanding falsy values is essential for writing effective conditional statements.

This lab guides you through listing common falsy values such as False, None, 0, 0.0, '', [], {}, and (). You'll create a Python script to iterate through these values and verify their falsy nature using an if statement. Furthermore, you'll explore how to use the not operator to check if a value is falsy. Finally, you'll learn how to test for falsy values using the bool() function.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/booleans -.-> lab-559593{{"How to Check If a Value Is Falsy in Python"}} python/conditional_statements -.-> lab-559593{{"How to Check If a Value Is Falsy in Python"}} python/build_in_functions -.-> lab-559593{{"How to Check If a Value Is Falsy in Python"}} python/data_collections -.-> lab-559593{{"How to Check If a Value Is Falsy in Python"}} end

List Common Falsy Values

In Python, certain values are considered "falsy," meaning they evaluate to False in a boolean context. Understanding falsy values is crucial for writing effective conditional statements and handling different data types. In this step, you'll learn about common falsy values in Python.

The following values are generally considered falsy in Python:

  • False: The boolean value False itself.
  • None: Represents the absence of a value or a null value.
  • 0: Integer zero.
  • 0.0: Float zero.
  • '': An empty string.
  • []: An empty list.
  • {}: An empty dictionary.
  • (): An empty tuple.

Let's create a Python script to explore these falsy values.

  1. Open your WebIDE.
  2. In the file explorer, navigate to the ~/project directory.
  3. Create a new file named falsy_values.py.

Now, let's add some Python code to this file:

## falsy_values.py

falsy_values = [False, None, 0, 0.0, '', [], {}, ()]

for value in falsy_values:
    if value:
        print(f"{value} is truthy")
    else:
        print(f"{value} is falsy")

This script iterates through a list of common falsy values and checks their boolean value using an if statement.

To run the script, open a terminal in your WebIDE (if you don't see one, click "Terminal" -> "New Terminal"). Then, execute the following command:

python falsy_values.py

You should see the following output:

False is falsy
None is falsy
0 is falsy
0.0 is falsy
 is falsy
[] is falsy
{} is falsy
() is falsy

This output confirms that all the values in the list are indeed considered falsy in Python.

Use not Operator

In Python, the not operator is a logical operator that negates the boolean value of its operand. It returns True if the operand is False, and False if the operand is True. This is particularly useful when you want to check if a value is falsy.

Let's modify the falsy_values.py script from the previous step to use the not operator.

  1. Open the falsy_values.py file in your WebIDE.

  2. Modify the script to include the not operator:

## falsy_values.py

falsy_values = [False, None, 0, 0.0, '', [], {}, ()]

for value in falsy_values:
    if not value:
        print(f"{value} is falsy")
    else:
        print(f"{value} is truthy")

In this modified script, the if not value: condition checks if the value is falsy. If value is falsy, not value evaluates to True, and the code inside the if block is executed. Otherwise, if value is truthy, not value evaluates to False, and the code inside the else block is executed.

To run the script, open a terminal in your WebIDE (if you don't see one, click "Terminal" -> "New Terminal"). Then, execute the following command:

python falsy_values.py

You should see the following output:

False is falsy
None is falsy
0 is falsy
0.0 is falsy
 is falsy
[] is falsy
{} is falsy
() is falsy

The output is the same as in the previous step, but now we are using the not operator to explicitly check for falsy values. This can make your code more readable and easier to understand.

Test with bool() Function

In Python, the bool() function is used to convert a value to a boolean (True or False). When you pass a value to bool(), it returns False if the value is falsy, and True if the value is truthy. This function provides a direct way to determine the boolean value of any object.

Let's modify the falsy_values.py script from the previous steps to use the bool() function.

  1. Open the falsy_values.py file in your WebIDE.

  2. Modify the script to use the bool() function:

## falsy_values.py

falsy_values = [False, None, 0, 0.0, '', [], {}, ()]

for value in falsy_values:
    boolean_value = bool(value)
    print(f"bool({value}) is {boolean_value}")

In this modified script, the bool(value) function converts each value in the falsy_values list to its boolean equivalent. The result is then stored in the boolean_value variable, which is printed to the console.

To run the script, open a terminal in your WebIDE (if you don't see one, click "Terminal" -> "New Terminal"). Then, execute the following command:

python falsy_values.py

You should see the following output:

bool(False) is False
bool(None) is False
bool(0) is False
bool(0.0) is False
bool() is False
bool([]) is False
bool({}) is False
bool(()) is False

This output demonstrates how the bool() function evaluates each of the falsy values to False.

Summary

In this lab, the initial step focuses on identifying common falsy values in Python, which include False, None, 0, 0.0, '', [], {}, and (). A Python script is created to iterate through a list containing these values, using an if statement to demonstrate that each of them evaluates to False in a boolean context. The script's output confirms the falsy nature of these values.

The lab then introduces the not operator, which negates the boolean value of its operand. This operator is useful for explicitly checking if a value is falsy by inverting its boolean representation.