# Set x equal to 15
x = 15
# Test if x is greater than 15
print(x > 15)False
This lesson introduces conditional logic in Python, showing how to use if, elif, else, comparison operators and logical operators to evaluate conditions.
Noor Sohail
Will Gammerdinger
March 16, 2026
if statements, elif, else, Comparison operators, Boolean logic
Approximate time: 60 minutes
In this lesson, we will:
if, elif and elsein operator to check for membership in a collectionConditional statements are what lets your code make decisions. In real projects, you might only run a quality‑control step if a file exists, flag samples that fail a cutoff or choose a different analysis path depending on user input. All of these rely on if, elif and else to check conditions and respond accordingly.
In this lesson, you will learn how to express True/False logic in Python so your scripts can adapt to different scenarios and datasets instead of inflexibly repeating the exact steps.
if statements will rely on the use of boolean logic. Typically we are checking if a variable is:
> or less than < a certain value>= or less than or equal to <= a certain value== a certain value!= a certain valueLet’s see this in action by testing :
We could test if x is less than or equal to 15 as well:
We can also compare strings with these conditional statements:
if StatementsIn Python, if is a key word that is off limits for variable names. It is used to create conditional statements, which allow us to execute certain blocks of code only when the specified conditions are met.
Essentially, we are evaluating whether or not a condition is True or False (as a boolean) and then executing code based on that result.
if StatementsWhen we want to check a condition, we can use an if statement. The basic syntax looks like this:
So if we wanted to check if x is greater than 10, we could write:
# Check if x is greater than 10
if x > 10:
# If true, print out 'x is greater than 10'
print('x is greater than 10')x is greater than 10
However, if the boolean logic returns false, then the conditional code will not be executed and thus nothing will be returned:
if statements are not exclusively numerical comparisons, we can check any boolean logic. So we could also test our my_name string from earlier:
# Check if my_name is equal to 'Anja'
if my_name == "Anja":
# If true, then print out this message
print("Hello, Anja!")Hello, Anja!
Additionally, we are not limited to only one line of code in a single code block. We can have as many lines of code as we want in a block, as long as they are all indented at the same level.
You may have noticed that the code block is indented. This is not just for the readability, it is actually required in Python. The indentation tells Python which lines of code belong to the if statement. If you forget to indent, you will get an error or the code will not execute as expected.
# If x is greater than 10
if x > 10:
# If true, then print this statement
# Note that it is not properly indented
print("x is greater than 10")expected an indented block after 'if' statement on line 2 (<string>, line 5)
We can also use nested if statements. Notice that the level of indentation is increased for the inner if statement and will need to continue to increase for each additional level of nesting. For example:
# If x is greater than 10
if x > 10:
# Print out this message
print("x is greater than 10")
# If x is less than 20
if x < 20:
# Print out this message
print("x is also less than 20")x is greater than 10
x is also less than 20
Create boolean logic to test whether x is NOT equal to 67.
Create an if statement that evaluates if x is NOT equal to 67 and if the number is not 67 then have it print “Your number is NOT 67.”
in OperatorThe in operator allows us to check if a value is present in a collection such as a list or a string. For example, if we wanted to check if the letter “o” is in the string “hello”, we could write:
# Check if the letter "o" exists in "hello"
if "o" in "hello":
# If true, print out this message
print("The letter 'o' is in the string 'hello'")The letter 'o' is in the string 'hello'
in can also be used to check if a value is in a list. We will discuss lists in more detail in the following lesson, but for now we will just assess whether or not a value is in a list like so:
# Create a list of integers called my_list
my_list = [1, 2, 3, 4, 5]
# Test if 3 is in my_list
3 in my_listTrue
As you saw, the in operator returns a boolean value (True or False) that indicates whether or not the value belongs to the list. This can be very useful for conditional statements, as we can use it to check if a value is in a list before trying to access it, which can help prevent errors. For example:
# Create a list called my list with some numbers in it
my_list = [1, 2, 3, 4, 5]
# Set x to 3
x = 3
# Check if x is in my_list list
if x in my_list:
# If true, print out this message
print(x, "is in the list!")3 is in the list!
my_name to be equal to Noor. Using the in operator and an if statement, check if there is an “o” within my_name. If true, have it return “I have found an ‘o’”.Hint: You may want to consider using single/double quotations for the entire print statement and using the other type of quotation mark around the “o”. Alternatively, you can look into escaping characters in Python.
elif and elseWe can join together the functionality of multiple if statements using elif and else. This allows us to check multiple conditions in a more efficient way without needing to nest multiple if statements.
else StatementsSometimes you may want to have a “catch-all” block of code that executes when the if statement is not met. This is where else comes in! We can build upon the “Alice” example from above and add an else statement to handle the case where name != "Alice":
elif StatementsSomewhat similarly to else, elif (short for “else if”) allows us to check multiple conditions in a sequence. The elif block will only be evaluated if the previous if or elif conditions were False. This allows us to check for multiple conditions without nesting multiple if statements. For example:
# Check if my_name matches 'Anja'
if my_name == 'Anja':
# If true, print this message
print('Hello, Anja!')
# Otherwise, check if my_name matches 'Noor'
elif my_name == 'Noor':
# If true, print this message
print('Hello, Noor!')
# Otherwise
else:
# Print this message
print("You aren't Anja or Noor!")Hello, Anja!
elif statements matter
You are not allowed to have an elif or else statement without a preceding if statement. However, you can have as many elif statements as you want in between the if and else statements. You are not required to include an else statement, but if you do, then it must be the last block in the sequence and it closes the if/elif/else chain.
In this example below, we will see that we have an if/else pair of statements, is followed by an elif statement. But the if/else pair of statements is a complete chain and now we have an elif without a preceeding if statement. This will return an error.
# Change my_name to a different name
my_name = 'Juan'
# Check if my_name matches 'Anja'
if my_name == 'Anja':
# If true, print this message
print('Hello, Anja!')
# Otherwise
else:
# Print this message
print("You aren't Alice or Bob!")
# Otherwise, check if my_name matches 'Noor'
# Note that this syntax of putting elif after the else is going to return an error on line 14
elif name == "Noor":
# If true, print this message
print("Hello, Bob!")invalid syntax (<string>, line 14)
Another nuanced, but important point is that when we use if, elif, and else statements together, the order of the conditions matters. Python will evaluate the conditions in the order they are written and once it finds a condition that is True, it will execute that block of code and skip the rest. For example:
# Check if x is greater than 10
if x > 10:
# If true, print this message
print("x is greater than 10")
# Otherwise, check if x is greater than 5
elif x > 5:
# If true, print this message
print("x is greater than 5 but not greater than 10")
# Otherwise
else:
# Print this message
print("x is 5 or less")x is 5 or less
Suppose we wanted to test if two things were True at the same time, or to see if at least one of two things were True. This is where logical operators are useful.
The and operator allows us to check if two conditions are both True, while the or operator allows us to check if at least one of two conditions is True. For example:
and OperatorLet’s use the example from earlier where we checked if x was greater than 10 and less than 20. We can use the and operator to check both conditions at the same time:
or OperatorIf we wanted to check if x was either less than 5 or greater than 10, we could use the or operator:
not OperatorThe not operator allows us to check if a condition is False and returns a True. For example, one way we could check if x is not greater than 10 would be to write:
This is sometimes more intuitive to read than writing x <= 10:.
We can also combine logical operators using parentheses to check multiple conditions at the same time. When we do this we need to be careful how we group those and and or statements together. Given these two statements when x is 15, the first example will return True:
# Set x to 15
x = 15
# Test if x is equal to 15 or if x is less than 20 and greater than 18
x == 15 or (x < 20 and x > 18)True
While the second example will return False:
# Test if x is equal to 15 or less than 20 and if x is greater than 18
(x == 15 or x < 20) and x > 18False
Create an if statement to evaluate whether x is between 5 and 10, inclusive of both 5 and 10. If so, have Python print out “x is between 5 and 10”.
Extend this same conditional to if x is not between 5 and 10, inclusively, but is above 10, then Python it print out “x is greater than 10”.
Extend this same conditional to if x is not between 5 and 10, inclusively, and also not above 10, then have Python return “x is less than 5”.
---
title: "Conditional Statements"
description: |
This lesson introduces conditional logic in Python, showing how to use if, elif, else, comparison operators and logical operators to evaluate conditions.
author:
- Noor Sohail
- Will Gammerdinger
date: "2026-03-16"
categories:
- Python programming
- Conditionals
- Boolean logic
keywords:
- if statements
- elif
- else
- Comparison operators
- Boolean logic
license: "CC-BY-4.0"
editor_options:
markdown:
wrap: 72
---
```{r}
#| label: load_libraries_data
#| echo: false
# Load libraries and data
```
Approximate time: 60 minutes
## Learning Objectives
In this lesson, we will:
- Create conditional statements using `if`, `elif` and `else`
- Use the `in` operator to check for membership in a collection
- Use logical operators to test multiple conditions at the same time
## Overview of lesson
Conditional statements are what lets your code make decisions. In real projects, you might only run a quality‑control step if a file exists, flag samples that fail a cutoff or choose a different analysis path depending on user input. All of these rely on `if`, `elif` and `else` to check conditions and respond accordingly.
In this lesson, you will learn how to express `True`/`False` logic in Python so your scripts can adapt to different scenarios and datasets instead of inflexibly repeating the exact steps.
## Boolean logic
`if` statements will rely on the use of boolean logic. Typically we are checking if a variable is:
- Greater than `>` or less than `<` a certain value
- Greater than or _equal_ to `>=` or less than or _equal_ to `<=` a certain value
- Equal to `==` a certain value
- Not equal to `!=` a certain value
Let's see this in action by testing :
```{python}
#| label: conditional_test_1
# Set x equal to 15
x = 15
# Test if x is greater than 15
print(x > 15)
```
We could test if `x` is less than or equal to `15` as well:
```{python}
#| label: conditional_test_2
# Test if x is less than or equal to 15
print(x <= 15)
```
We can also compare strings with these conditional statements:
```{python}
#| label: conditional_test_string
# Set the string 'Anja' to a variable called my_name
my_name = 'Anja'
# Test if my_name variable is equal to 'Anja'
print(my_name == 'Anja')
```
## `if` Statements
In Python, `if` is a key word that is off limits for variable names. It is used to create conditional statements, which allow us to execute certain blocks of code only when the specified conditions are met.
Essentially, we are evaluating whether or not a condition is `True` or `False` (as a boolean) and then executing code based on that result.
### Syntax of `if` Statements
When we want to check a condition, we can use an `if` statement. The basic syntax looks like this:
```{python}
#| label: if_statement_syntax
#| eval: false
# DO NOT RUN
if condition:
# code to execute if condition is true
```
So if we wanted to check if `x` is greater than 10, we could write:
```{python}
#| label: if_statement_example
# Check if x is greater than 10
if x > 10:
# If true, print out 'x is greater than 10'
print('x is greater than 10')
```
However, if the boolean logic returns false, then the conditional code will not be executed and thus nothing will be returned:
```{python}
#| label: if_statement_fail_example
# Check if x is greater than 10
if x <= 10:
# If true, print out 'x is greater than 10'
print('x is greater than 10')
```
`if` statements are not exclusively numerical comparisons, we can check any boolean logic. So we could also test our `my_name` string from earlier:
```{python}
#| label: if_statement_string_example
# Check if my_name is equal to 'Anja'
if my_name == "Anja":
# If true, then print out this message
print("Hello, Anja!")
```
Additionally, we are not limited to only one line of code in a single code block. We can have as many lines of code as we want in a block, as long as they are all indented at the same level.
```{python}
#| label: if_statement_multiple_lines
# If my_name is equal to Anja
if my_name == 'Anja':
# If true, print out these two statements
print('Hello, Anja!')
print('Welcome to the Python training!')
```
### Indentation Matters
You may have noticed that the code block is indented. This is not just for the readability, it is actually required in Python. The indentation tells Python which lines of code belong to the `if` statement. If you forget to indent, you will get an error or the code will not execute as expected.
```{python}
#| label: if_statement_indentation_error
#| error: true
# If x is greater than 10
if x > 10:
# If true, then print this statement
# Note that it is not properly indented
print("x is greater than 10")
```
We can also use nested `if` statements. Notice that the level of indentation is increased for the inner `if` statement and will need to continue to increase for each additional level of nesting. For example:
```{python}
#| label: nested_if_statement
# If x is greater than 10
if x > 10:
# Print out this message
print("x is greater than 10")
# If x is less than 20
if x < 20:
# Print out this message
print("x is also less than 20")
```
:::{.callout-tip}
# [**Exercise 1**](03_conditional_statements-Answer_key.qmd#exercise-1)
1. Create boolean logic to test whether `x` is ***NOT*** equal to `67`.
2. Create an `if` statement that evaluates if `x` is ***NOT*** equal to `67` and if the number is not `67` then have it print "Your number is NOT 67."
:::
### `in` Operator
The `in` operator allows us to check if a value is present in a collection such as a list or a string. For example, if we wanted to check if the letter "o" is in the string "hello", we could write:
```{python}
#| label: in_operator_example
# Check if the letter "o" exists in "hello"
if "o" in "hello":
# If true, print out this message
print("The letter 'o' is in the string 'hello'")
```
`in` can also be used to check if a value is in a list. We will discuss lists in more detail in the following lesson, but for now we will just assess whether or not a value is in a list like so:
```{python}
#| label: in_operator_list_example
# Create a list of integers called my_list
my_list = [1, 2, 3, 4, 5]
# Test if 3 is in my_list
3 in my_list
```
As you saw, the `in` operator returns a boolean value (`True` or `False`) that indicates whether or not the value belongs to the list. This can be very useful for conditional statements, as we can use it to check if a value is in a list before trying to access it, which can help prevent errors. For example:
```{python}
#| label: in_operator_conditional_example
# Create a list called my list with some numbers in it
my_list = [1, 2, 3, 4, 5]
# Set x to 3
x = 3
# Check if x is in my_list list
if x in my_list:
# If true, print out this message
print(x, "is in the list!")
```
:::{.callout-tip}
# [**Exercise 2**](03_conditional_statements-Answer_key.qmd#exercise-2)
1. Set `my_name` to be equal to `Noor`. Using the `in` operator and an `if` statement, check if there is an "o" within `my_name`. If true, have it return "I have found an 'o'".
*Hint: You may want to consider using single/double quotations for the entire print statement and using the other type of quotation mark around the "o". Alternatively, you can look into escaping characters in Python.*
2. We can see that there are two "o"s in Noor. So, one might expect there to be two "I have found an 'o'" statements, but we only see one. Why is this?
:::
## Multiple Conditions with `elif` and `else`
We can join together the functionality of multiple `if` statements using `elif` and `else`. This allows us to check multiple conditions in a more efficient way without needing to nest multiple `if` statements.
### `else` Statements
Sometimes you may want to have a "catch-all" block of code that executes when the `if` statement is not met. This is where `else` comes in! We can build upon the "Alice" example from above and add an `else` statement to handle the case where `name != "Alice"`:
```{python}
#| label: if_else_example
# Check if my_name matches 'Anja'
if my_name == 'Anja':
# If true, print this message
print('Hello, Anja!')
# Otherwise, do this
else:
# Print this message
print("You are not Anja!")
```
### `elif` Statements
Somewhat similarly to `else`, `elif` (short for "else if") allows us to check multiple conditions in a sequence. The `elif` block will only be evaluated if the previous `if` or `elif` conditions were `False`. This allows us to check for multiple conditions without nesting multiple `if` statements. For example:
```{python}
#| label: elif_example
# Check if my_name matches 'Anja'
if my_name == 'Anja':
# If true, print this message
print('Hello, Anja!')
# Otherwise, check if my_name matches 'Noor'
elif my_name == 'Noor':
# If true, print this message
print('Hello, Noor!')
# Otherwise
else:
# Print this message
print("You aren't Anja or Noor!")
```
:::{.callout-note}
#### Placement of `elif` statements matter
You are not allowed to have an `elif` or `else` statement without a preceding `if` statement. However, you can have as many `elif` statements as you want in between the `if` and `else` statements. You are not required to include an `else` statement, but if you do, then it must be the last block in the sequence and it closes the `if`/`elif`/`else` chain.
In this example below, we will see that we have an `if`/`else` pair of statements, is followed by an `elif` statement. But the `if`/`else` pair of statements is a complete chain and now we have an `elif` without a preceeding `if` statement. This will return an error.
```{python}
#| label: multiple_elif_example
#| error: true
# Change my_name to a different name
my_name = 'Juan'
# Check if my_name matches 'Anja'
if my_name == 'Anja':
# If true, print this message
print('Hello, Anja!')
# Otherwise
else:
# Print this message
print("You aren't Alice or Bob!")
# Otherwise, check if my_name matches 'Noor'
# Note that this syntax of putting elif after the else is going to return an error on line 14
elif name == "Noor":
# If true, print this message
print("Hello, Bob!")
```
:::
### Order Matters
Another nuanced, but important point is that when we use `if`, `elif`, and `else` statements together, the order of the conditions matters. **Python will evaluate the conditions in the order they are written** and once it finds a condition that is `True`, it will execute that block of code and skip the rest. For example:
```{python}
#| label: elif_order_example
# Check if x is greater than 10
if x > 10:
# If true, print this message
print("x is greater than 10")
# Otherwise, check if x is greater than 5
elif x > 5:
# If true, print this message
print("x is greater than 5 but not greater than 10")
# Otherwise
else:
# Print this message
print("x is 5 or less")
```
## Logical Operators
Suppose we wanted to test if two things were `True` at the same time, or to see if at least one of two things were `True`. This is where logical operators are useful.
The `and` operator allows us to check if two conditions are both `True`, while the `or` operator allows us to check if at least one of two conditions is `True`. For example:
### `and` Operator
Let's use the example from earlier where we checked if `x` was greater than 10 and less than 20. We can use the `and` operator to check both conditions at the same time:
```{python}
#| label: and_operator_example
# Test if x is greater than 10 and x is less than 20
x > 10 and x < 20
```
### `or` Operator
If we wanted to check if `x` was either less than 5 or greater than 10, we could use the `or` operator:
```{python}
#| label: or_operator_example
# Test if x is less than 5 or x is greater than 10
x < 5 or x > 10
```
### `not` Operator
The `not` operator allows us to check if a condition is `False` and returns a `True`. For example, one way we could check if `x` is not greater than 10 would be to write:
```{python}
#| label: not_operator_example
# Test if x is NOT greater than 10
not x > 10
```
This is sometimes more intuitive to read than writing `x <= 10:`.
### Combining Logical Operators
We can also combine logical operators using parentheses to check multiple conditions at the same time. When we do this we need to be careful how we group those `and` and `or` statements together. Given these two statements when `x` is `15`, the first example will return `True`:
```{python}
#| label: combined_logical_operators_example_1
# Set x to 15
x = 15
# Test if x is equal to 15 or if x is less than 20 and greater than 18
x == 15 or (x < 20 and x > 18)
```
While the second example will return `False`:
```{python}
#| label: combined_logical_operators_example_2
# Test if x is equal to 15 or less than 20 and if x is greater than 18
(x == 15 or x < 20) and x > 18
```
:::{.callout-tip}
# [**Exercise 3**](03_conditional_statements-Answer_key.qmd#exercise-3)
1. Create an `if` statement to evaluate whether `x` is between 5 and 10, inclusive of both 5 and 10. If so, have Python print out "x is between 5 and 10".
2. Extend this same conditional to if `x` is not between 5 and 10, inclusively, but is above 10, then Python it print out "x is greater than 10".
3. Extend this same conditional to if `x` is not between 5 and 10, inclusively, and also not above 10, then have Python return "x is less than 5".
:::
***
[Next Lesson >>](04_data_structures.qmd)
[Back to Schedule](../schedule/schedule.qmd)