Lesson 5 - Conditional Statements

In this new lesson, we’re going to learn how to write programs that can make decisions.

To do this, we’ll cover:

  • How to use if, else, and elif statements
  • How to compare values using comparison operators
  • How to combine conditions using logical operators

These tools help us build programs that can check conditions and behave differently depending on the data. You’ll use this a lot when analyzing real-world data.

We’ll use a dataset called bookstore_apps.csv (Download Here). This file contains information about fictional apps from a digital bookstore. Here’s a quick look at what the data looks like:

titlepricecurrencytotal_reviewsavg_ratinggenre
Desert Echoes0.00USD1,755,1444.4Productivity
Shattered Wings1.99USD1,744,4924.1Health & Fitness
Moon Over Pine29.99USD1,084,8344.0Games

Let’s say we want to know the average rating of free apps. First, we need to:

  1. Go through each row in the dataset
  2. Check if the price is 0
  3. If it is, save the app’s rating in a list
  4. Then calculate the average rating from that list

To do this, we use something called an if statement.

Using if Statements

Let’s start by loading the data and collecting all the ratings into a list.

import csv

with open("bookstore_apps.csv") as f:
    reader = csv.reader(f)
    apps_data = list(reader)

header = apps_data[0]
apps_data = apps_data[1:]

ratings = []
for row in apps_data:
    rating = float(row[4])
    ratings.append(rating)

But this gives us ratings for all apps. What we want is just the ratings for free apps.

To do that, we add a condition:

free_ratings = []

for row in apps_data:
    price = float(row[1])
    rating = float(row[4])

    if price == 0.0:
        free_ratings.append(rating)

In this example, we:

  • Check if the app is free using if price == 0.0
  • If the condition is true, we add the rating to our free_ratings list

Important Notes

  • The if line ends with a colon :
  • The line underneath must be indented (this shows it runs only when the condition is true)
  • == means “is equal to” (don’t confuse it with = which is used to assign a value)

Now let’s calculate the average rating of the free apps:

avg_rating_free = sum(free_ratings) / len(free_ratings)
print(avg_rating_free)

This gives us a number that tells us what users think of the free apps in general.

Try it yourself

Below is a small coding task. Fill in the missing parts to practice using if statements:

free_ratings = []

for row in apps_data:
    # Your code here

    if price == 0.0:
        # Your code here

avg_rating_free = sum(free_ratings) / len(free_ratings)
print(avg_rating_free)

In the next section, we’ll talk about Booleans and what makes if statements work under the hood.


Booleans

In the first section, we used a condition like price == 0.0 in an if statement to check if an app was free.

This kind of check gives us a result that’s either True or False. These are known as Boolean values. They’re not strings, even though they look like words — they are part of a special data type in Python called bool.

Let’s look at a simple example:

print(4 == 4)
print(4 == 7)

Output:

True
False

The first line checks if 4 is equal to 4. That’s true, so it prints True.

The second line checks if 4 is equal to 7. That’s false, so it prints False.

We can also check the type of these values:

print(type(True))
print(type(False))

Output:

<class 'bool'>
<class 'bool'>

This tells us that True and False are not just words. They’re values of a special type: bool, which is short for Boolean.

Why Booleans Matter

Whenever you write an if statement, Python expects one of two things after the if keyword:

  • A Boolean value like True or False
  • Or something that turns into a Boolean value (like price == 0.0)

Here’s an example with a variable:

price = 0

print(price == 0)
print(price == 2)

Output:

True
False

Now we can use this in an if statement:

a_price = 0

if a_price == 0:
    print("This is free")

if a_price == 1:
    print("This is not free")

Only the first message will appear, because only the first condition is true.

Indentation

When you use if, make sure the lines underneath are indented (pushed to the right). In Python, we usually use 4 spaces to do this. All indented lines are part of the if block and will only run if the condition is true.


The Average Rating of Non-free Apps

In the last section, we found the average rating of free apps using this condition:

if price == 0.0:

Now let’s do the opposite. What if we want to know how people rate paid apps — the ones that cost money?

To get that, we need to look at rows where the price is not equal to 0.0. In Python, we use != to mean “not equal to.”

Let’s try it:

paid_ratings = []

for row in apps_data:
    price = float(row[1])
    rating = float(row[4])

    if price != 0.0:
        paid_ratings.append(rating)

avg_rating_paid = sum(paid_ratings) / len(paid_ratings)
print(avg_rating_paid)

What this code does

  • It creates an empty list called paid_ratings
  • Then it loops through the dataset
  • It checks if the price is not 0.0
  • If that’s true, it adds the rating to the list
  • After the loop, it calculates the average rating of all paid apps

This is a great example of how changing a small part of your condition (!= instead of ==) lets you answer a totally different question with the same code structure.


The Average Rating of Apps in a Genre (e.g., Games)

Sometimes we want to analyze only a specific group of apps. For example, we might want to know what users think about apps in the Games genre.

In our dataset, each app has a genre, and it’s stored in the last column of every row (row[5]). To find the average rating of apps in a specific genre, we need to:

  1. Loop through the dataset
  2. Check if the genre is equal to "Games"
  3. If it is, save the rating in a list
  4. At the end, calculate the average of that list

Let’s write this in code:

games_ratings = []

for row in apps_data:
    genre = row[5]
    rating = float(row[4])

    if genre == 'Games':
        games_ratings.append(rating)

avg_rating_games = sum(games_ratings) / len(games_ratings)
print(avg_rating_games)

What’s happening here

  • We created an empty list called games_ratings
  • For each row, we pulled out:
    • The genre → row[5]
    • The average rating → row[4]
  • We checked if the genre was 'Games'
  • If it was, we added the rating to our list
  • After the loop, we calculated the average rating using sum(...) / len(...)

This helps us answer a very specific question: “What’s the average rating of all apps that belong to the Games category?”

This method can be repeated with other genres too. Just change 'Games' to any other genre in the dataset, such as 'Music', 'Productivity', or 'Health & Fitness'.

What if the genre is not equal to Games?

If we want to look at non-gaming apps, we can change the condition to:

if genre != 'Games':

This would give us the ratings for everything that is not a game.


Multiple Conditions (e.g., Free Gaming Apps)

Sometimes we want to filter our data based on more than one rule at the same time. For example:

  • What if we want to find the average rating of apps that are both free and in the Games genre?

In Python, we use the and keyword when we want multiple conditions to be true at the same time.

Let’s break it down:

  • We only want apps where the genre is "Games"
  • And where the price is 0.0

Here’s how we write that:

free_games_ratings = []

for row in apps_data:
    price = float(row[1])
    rating = float(row[4])
    genre = row[5]

    if genre == 'Games' and price == 0.0:
        free_games_ratings.append(rating)

avg_free_games = sum(free_games_ratings) / len(free_games_ratings)
print(avg_free_games)

How it works

  • genre == 'Games' and price == 0.0 checks both conditions
  • If both are true, we add the rating to our list
  • At the end, we compute the average just like before

Let’s say an app is:

  • In the Games category ✔
  • And free ✔

→ The condition is True and the rating gets added.

But if even one of them is false, the rating is skipped.

Try adjusting the logic

You can use this approach to ask other combined questions, such as:

  • Paid apps in the Games genre:

    if genre == 'Games' and price != 0.0
  • Free apps in any genre except Games:

    if genre != 'Games' and price == 0.0

We’ll keep building on this in the next section, where we look at another keyword: or.


The or Operator

In the last section, we used the and operator to combine two conditions — both had to be true.

Now let’s look at situations where we want to do something if at least one condition is true.

That’s where the or operator comes in.

Let’s say we want to analyze apps that are either in the Games genre or the Social Networking genre.

We can write that like this:

selected_ratings = []

for row in apps_data:
    genre = row[5]
    rating = float(row[4])

    if genre == 'Games' or genre == 'Social Networking':
        selected_ratings.append(rating)

avg_selected = sum(selected_ratings) / len(selected_ratings)
print(avg_selected)

Explanation

  • The or operator checks if either condition is true
  • If the app is in the Games genre — it’s included ✅
  • If the app is in the Social Networking genre — it’s also included ✅
  • If neither — it’s ignored ❌

This is useful when you want to group two types of apps together and treat them as one category.

Combining and and or

You can also combine and and or together, but be careful with how you write the condition. Python checks things in order, so it’s a good habit to use parentheses to group logic clearly:

if (genre == 'Games' or genre == 'Social Networking') and price == 0.0:

This condition means:

  • The app is either in Games or Social Networking
  • And it is free

We’ll explore more combinations like that in the next section.


Combining Logical Operators

Now that you’ve learned about both and and or, you can combine them to make more complex decisions.

Let’s say we want to find apps that meet two combined rules:

  • The genre is either "Games" or "Social Networking"
  • And the app is not free

We can write that like this:

selected_paid_ratings = []

for row in apps_data:
    genre = row[5]
    price = float(row[1])
    rating = float(row[4])

    if (genre == 'Games' or genre == 'Social Networking') and price != 0.0:
        selected_paid_ratings.append(rating)

avg_selected_paid = sum(selected_paid_ratings) / len(selected_paid_ratings)
print(avg_selected_paid)

How this works

  • We wrapped the or conditions in parentheses: (genre == 'Games' or genre == 'Social Networking')
  • Then we combined that whole group with and price != 0.0

This tells Python: “First check the genre — it should be one of the two. Then also check that the app is paid.”

Without the parentheses, Python would get confused and might run the logic in a different order than we expect.

Important: Always Use Parentheses When Mixing and and or

Let’s compare two conditions:

✅ This is correct:

if (genre == 'Games' or genre == 'Social Networking') and price == 0.0:

❌ This is not safe:

if genre == 'Games' or genre == 'Social Networking' and price == 0.0:

In the second example, Python will first check if the genre is exactly 'Games', or if 'Social Networking' and price == 0.0 — which isn’t what you meant.

Using parentheses makes your logic clear and avoids bugs.


The not Operator

Sometimes, you want to select all the items that don’t meet a condition. That’s where the not operator comes in.

It simply reverses the result of a condition:

  • not True becomes False
  • not False becomes True

Let’s look at an example first:

print(not True)   # False
print(not False)  # True

This is useful when you want to exclude a group instead of including it.

A Real Example

Let’s say we want to calculate the average rating of non-free apps that are not in the Games or Social Networking genres.

In plain English:

  • The app should not belong to either of these genres
  • And it must be a paid app

Here’s how we write that:

other_paid_ratings = []

for row in apps_data:
    genre = row[5]
    price = float(row[1])
    rating = float(row[4])

    if not (genre == 'Games' or genre == 'Social Networking') and price != 0.0:
        other_paid_ratings.append(rating)

avg_other_paid = sum(other_paid_ratings) / len(other_paid_ratings)
print(avg_other_paid)

How this works

  • The part inside the parentheses:

    genre == 'Games' or genre == 'Social Networking'

    is True for gaming or social apps.

  • not (...) flips that to False, so those apps are skipped.

  • Then and price != 0.0 makes sure the app is paid.

So in the end, only paid apps not in Games or Social Networking are included.


Comparison Operators

So far, we’ve used the == and != operators to compare values. But Python supports other comparison operators that are very useful when working with numbers.

Let’s go over them:

OperatorMeaningExample
==Equal toprice == 0.0
!=Not equal togenre != 'Games'
>Greater thanrating > 4.0
<Less thanprice < 10.0
>=Greater than or equalrating >= 4.5
<=Less than or equalprice <= 20.0

These comparison operators are often used in filtering data. For example, you can check which apps have very high ratings or which ones are too expensive.

Let’s look at a few examples:

print(5 > 1)       # True
print(3 < 2)       # False
print(10 >= 10)    # True
print(9.5 <= 10.0) # True

Example: Count how many apps have high ratings

Suppose we want to count how many apps have an average rating of 4.0 or higher.

Here’s how we could do it:

high_rating_count = 0

for row in apps_data:
    rating = float(row[4])

    if rating >= 4.0:
        high_rating_count += 1

print(high_rating_count)

Example: Compare prices

You can also filter based on price. For instance, you might want to look at very expensive apps (more than $20) or affordable ones (less than or equal to $9.99).

expensive_apps = []
affordable_apps = []

for row in apps_data:
    price = float(row[1])
    title = row[0]

    if price > 20.0:
        expensive_apps.append(title)

    if price <= 9.99:
        affordable_apps.append(title)

This gives us two lists:

  • One with apps that are considered expensive
  • One with apps that are affordable

These comparison operators help you slice and dice your dataset in many useful ways.


The else Clause

So far, we’ve used if to run a block of code when a condition is true. But what if we want to run a different block of code when the condition is false?

That’s where the else clause comes in.

It lets us say: “Do one thing if the condition is true — otherwise, do something else.”

Example

Let’s say we want to label each app as either "free" or "non-free", based on its price.

apps_labeled = []

for row in apps_data:
    price = float(row[1])
    label = ''

    if price == 0.0:
        label = 'free'
    else:
        label = 'non-free'

    apps_labeled.append([row[0], price, label])

for app in apps_labeled[:5]:
    print(app)

What’s happening here?

  • We loop through the data
  • For each app, we check if the price is 0.0
  • If it is, we label it 'free'
  • Otherwise (with else), we label it 'non-free'
  • Then we store the result in a new list

This is helpful when you need to sort or classify items into two categories.

Important points

  • You must use else after an if block
  • You don’t write a condition with else — it catches everything else
  • The else block must be indented, just like if

This allows your code to react to both cases — when a condition is true and when it’s not.


The elif Clause

We’ve seen how if lets us check one condition, and else lets us catch everything else. But what if we need to check for three or more possibilities?

That’s when we use elif, which stands for “else if”.

Why use elif?

Let’s say we want to label apps based on their price:

  • If the price is 0.0, label it as "free"
  • If the price is greater than 0.0 but less than 20.0, label it as "affordable"
  • If the price is between 20.0 and 50.0, label it as "expensive"
  • If the price is 50.0 or more, label it as "very expensive"

We can use multiple elif blocks to describe each case clearly.

Example

price_labels = []

for row in apps_data:
    title = row[0]
    price = float(row[1])

    if price == 0.0:
        label = 'free'
    elif price > 0.0 and price < 20.0:
        label = 'affordable'
    elif price >= 20.0 and price < 50.0:
        label = 'expensive'
    else:
        label = 'very expensive'

    price_labels.append([title, price, label])

for app in price_labels[:5]:
    print(app)

Output sample

['Desert Echoes', 0.0, 'free']
['Shattered Wings', 1.99, 'affordable']
['Moon Over Pine', 29.99, 'expensive']
['Emerald Song', 54.99, 'very expensive']
...

How it works

  • Python checks the first if condition
  • If it’s false, it checks the next elif
  • If none of the if or elif conditions match, the else block runs

This structure lets you cover multiple options clearly and efficiently.


Next Steps

You’ve now completed a full lesson on conditional statements in Python!

Let’s quickly review what you’ve learned:

  • Boolean values like True and False are at the heart of every condition
  • if lets you run code when something is true
  • else gives you an alternative when the condition is false
  • elif allows you to check multiple possibilities in order
  • You used comparison operators like ==, !=, >, and < to compare values
  • You learned how to combine conditions using and, or, and not
  • You wrote real programs that worked with a dataset and answered practical questions

Here are some examples of the kinds of questions you answered with code:

  • What is the average rating of free apps?
  • What is the average rating of paid apps?
  • How do apps in the Games genre compare to other categories?
  • Can we filter apps that are either social or games — and only show the free ones?
  • How can we label every app by price level?

These are the kinds of skills you’ll use when analyzing data, building dashboards, training machine learning models, or even working in backend development.


In the next lesson, you’ll learn how to loop through multiple rows of data more efficiently and begin to explore more advanced data structures like dictionaries — an essential part of any real-world Python project.

Take a break, then come back ready for the next step in your journey!