2.1 If Statements

Controlling Python’s Flow

If statements are the simplest form of flow control in Python. They allow you to execute certain blocks of code based on whether a condition is True or False. They accept boolean expressions to determine which code to execute. We have already gone over the various aspects of boolean expressions, but we need to understand truthy and falsy values before we can fully dive into if statements.

Truthy and Falsy Values

In Python, certain values are considered “truthy” or “falsy.” A truthy value evaluates to True in a boolean context, while a falsy value evaluates to False. The following values are considered falsy:

  • None
  • False
  • Numeric zero values (0, 0.0)
  • Empty collections (e.g., [], {}, set(), "")

All other values are considered truthy. This distinction is important when using conditional statements, as it determines whether a condition evaluates to True or False. Another way of saying this is that we can check if a string is empty by simply using the string variable in a conditional statement.

my_string = ""
if my_string:
    print("String is not empty")
else:
    print("String is empty")
String is empty

We could do the same to see if a list is empty:

my_list = []
if my_list:
    print("List is not empty")
else:
    print("List is empty")
List is empty

Understanding and using truthy and falsy values can simplify your code and make it more readable, as you can avoid explicit comparisons to True or False. These if statements are actually checking two separate conditions: does the variable exist, and is there something there? It replaces the need for more verbose checks like if my_string and my_string != "", or if my_list and len(my_list) > 0. We can simply write if my_string: or if my_list: to check if they exist and are not empty.

Basic If Statements

There are three parts to an if statement: the if keyword, the elif keyword, and the else keyword. The if keyword is used to start the conditional statement, the elif keyword is used to add additional conditions, and the else keyword is used to provide a default action if none of the previous conditions are met. Following each keyword is a boolean expression that evaluates to either True or False. If the expression evaluates to True, the code block under that condition is executed. If it evaluates to False, the program moves on to the next condition, if there is one. See below for an example.

x = True
y = False

if y:
    print("x is True")
elif x:
    print("y is True")
else:
    print("Neither x nor y is True")
y is True

In this example, the first condition checks if y is True. Since y is False, it moves to the next condition, which checks if x is True. Since x is True, it prints “y is True”. If both conditions were False, it would print “Neither x nor y is True”. Once the Python interpreter finds an if or elif statement that evaluates to True, it will no longer evaluate the rest of the if statement.

It is important to provide an else statement as a default action if none of the previous conditions are met. This ensures that your code has a defined behavior even when none of the conditions are satisfied. If you do not provide an else statement, and none of the conditions are met, the program will simply skip the entire if statement without executing any code. Sometimes this can be a desirable result, but we will discuss those further later.

For instance, if we have only two options, we can use an if-else statement to handle both cases:

x = True
if x:
    print("x is True")
else:
    print("x is False")
x is True

This code checks if x is True. If it is, it prints “x is True”. If x is False, it prints “x is False”. This is a simple way to handle two possible outcomes.

Nested if Statements

You can also nest if statements within each other to create more complex conditions. This allows you to check multiple conditions in a hierarchical manner. Here’s an example:

x = True
y = False

if x:
    if y:
        print("Both x and y are True")
    else:
        print("x is True, but y is False")
else:
    if y:
        print("x is False, but y is True")
    else:
        print("Both x and y are False")
x is True, but y is False

In this example, we first check if x is True. If it is, we then check if y is also True. If both are True, it prints “Both x and y are True”. If x is True but y is False, it prints “x is True, but y is False”. The same logic applies for when x is False.

One line if Statements

You can also write simple if statements in a single line using the ternary operator. This is useful for short conditions where you want to assign a value based on a condition. It is frequently used as a way to dynamically instantiate a variable. To do so, we start with the desired value if else the default value. See below.

x = True
result = 5 if x else 10

Only one line of code is executed here, and it assigns 5 to result if x is True, otherwise it assigns 10. This is a concise way to handle simple conditions without needing a full if statement. It can only handle two options.