Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Conditional Logic with If/Else

Recommended resources

Hello! Welcome to your second lesson.

In our last session, we learned how to store information using variables and basic data types. We ended by creating a script that determined if a user was an adult and stored that True or False value in a boolean variable. That was a crucial first step toward making our programs "intelligent."

Today, we'll learn how to make our programs act on those True or False values. You will learn how to use conditional statements (if, elif, and else) to control which parts of your code run. This is called controlling the program flow, and it's how you make your programs respond dynamically to different situations. For your goal of building a text analysis tool, this is fundamental. For example, your app will need to decide: "if the user enters text, analyze it; else, show an error message."

The Core of Decision Making: Conditions

A conditional statement checks if a certain condition is true. A condition is simply an expression that evaluates to either True or False. We create these conditions using comparison operators.

In our last lesson, the line is_adult = user_age_int >= 18 contained the condition user_age_int >= 18. The >= (greater than or equal to) is a comparison operator.

To see the full set of comparison operators you can use, the article below provides a clear and concise reference.

Chapter 2 - if-else and Flow Control

This chapter from the book 'Automate the Boring Stuff with Python' explains the building blocks of conditional logic. For now, we will focus on the operators used to create conditions.

Read the section titled 'Comparison Operators' and review the table of operators (==, !=, <, >, <=, >=). Note the difference between the comparison operator == (is it equal?) and the assignment operator = (store this value).


The if Statement: The Simplest Decision

The if statement is the most basic control structure. It tells the program: "If this condition is true, then execute the block of code that follows." If the condition is false, the code block is simply skipped.

A crucial part of Python's syntax is indentation. The code that "belongs" to the if statement must be indented (usually with four spaces). This is how Python knows which lines to execute when the condition is true.

user_age = 20

# The condition is user_age >= 18, which is True.
if user_age >= 18:
    # This indented block will be executed.
    print("You are eligible to vote.")

# This line is not indented, so it runs regardless of the 'if' statement.
print("Program finished.")

if and else: Providing an Alternative Path

What if you want to do something else when the condition is false? That's what the else statement is for. It gives the program an alternative path to follow.

The video below provides a clear, practical introduction to if and else statements.

If statements in Python are easy (if, elif, else) 🤔

This video from Bro Code walks through the basics of if and else using a simple age-checking example.

Watch from the beginning to the 2:21 mark. Pay close attention to how the else block provides a path for when the if condition is not met.

As you saw in the video, the structure looks like this:

password_attempt = "12345"

if password_attempt == "correct_password":
    print("Access granted.")
else:
    # This block runs because the 'if' condition was False.
    print("Access denied. Incorrect password.")

elif: Handling More Than Two Possibilities

Sometimes, you need to check several different conditions. You could have a program that needs to respond differently to "good morning," "good afternoon," and "good evening." This is where elif (short for "else if") comes in.

You can use as many elif statements as you need. Python will check each condition in order, from top to bottom. As soon as it finds a condition that is True, it will execute that block of code and then skip the rest of the if/elif/else chain.

This next part of the Bro Code video introduces elif and highlights an important point about the order of your conditions.

If statements in Python are easy (if, elif, else) 🤔

Let's continue with the same video to see how elif allows us to check for multiple conditions.

Watch from 2:21 to 4:17. Notice how changing the order of the elif statements can change the program's output.

Here is a visual representation of how an if/elif/else structure works. The program flow moves from one condition to the next until one is met or it reaches the final else block.

Python If-Else-Elif with Flowchart
This image shows a Python code snippet on the left and a corresponding flowchart on the right, illustrating how the program makes decisions at each conditional step (`if`, `elif`, `else`).

Let's look at a classic example of grading a test score:

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    # This condition is True, so this block runs.
    print("Grade: B")
elif score >= 70:
    # This block and the 'else' block are skipped.
    print("Grade: C")
else:
    print("Grade: F")

Because the score is 85, the first condition (>= 90) is false. Python moves to the next condition, score >= 80, which is true. It prints "Grade: B" and then skips the rest of the chain.

Test your understanding!

Imagine you are writing a simple program for a coffee shop. Given the following code, what will it print if order_size is set to "Medium"?

order_size = "Medium"
price = 0

if order_size == "Small":
    price = 2
elif order_size == "Medium":
    price = 3
elif order_size == "Large":
    price = 4
else:
    print("Sorry, we don't have that size.")

if price > 0:
    print(f"Your total is ${price}.")
Show answer

The program will print: Your total is $3.

Here's the step-by-step logic:

  1. The first if condition (order_size == "Small") is false.
  2. The first elif condition (order_size == "Medium") is true. The code inside this block runs, setting price to 3.
  3. The rest of the if/elif/else chain is skipped.
  4. The program continues to the final if statement. The condition price > 0 (is 3 > 0?) is true, so it prints the final message.

Try It Yourself: A Simple Chatbot

Now let's put this all together to create a simple, interactive program. This is a small step toward your goal of building an AI-powered tool. We'll make a chatbot that can respond to a few specific phrases.

The following video creates a similar project. Watch how it uses an if/elif/else structure to handle different user inputs.

Learn Python in Only 30 Minutes (Beginner Tutorial)

This video from Indently demonstrates how if/elif/else is used to create a simple chatbot that can understand different user inputs.

Watch the section from 17:18 to 18:57. Focus on how the program's response changes based on the value of the user_input variable.

Now, try to write this code yourself.

  1. Create a new file in VS Code called chatbot.py.
  2. Write a program that does the following:
    • Asks the user for input with the prompt: Talk to the bot:
    • Converts the user's input to lowercase to make the conditions simpler (e.g., so that "Hello" and "hello" are treated the same).
    • If the user types "hello", the bot should respond with "Hi there!".
    • If the user types "how are you?", the bot should respond with "I'm a bot, I'm doing great!".
    • If the user types "bye", the bot should respond with "Goodbye!".
    • For any other input, the bot should respond with "Sorry, I don't understand that."

You can use the code below as a starting point. Try to fill in the ... parts.

# Get user input and convert to lowercase
user_input = input("Talk to the bot: ").lower()

# Check the user's input and respond
if user_input == "...":
    print("Hi there!")
elif ...:
    print("I'm a bot, I'm doing great!")
elif ...:
    ...
else:
    ...

Key Takeaways

Excellent work! You've just learned one of the most powerful concepts in programming.

  • Conditional statements (if, elif, else) allow your program to make decisions and run different code based on different conditions.
  • Conditions are expressions that evaluate to True or False, often created using comparison operators (==, >, <=, etc.).
  • The if block runs if a condition is true.
  • The else block provides an alternative path if the if condition is false.
  • The elif block allows you to check for multiple different conditions in a sequence.
  • Indentation is critical in Python. It defines which code blocks belong to which statements.

Next Steps

So far, we've worked with single pieces of data—one name, one age, one line of text. But what if you want to work with a list of names, or all the words in a document?

In the next lesson, we will explore lists and dictionaries. These are data structures that allow you to store and manage collections of data, which will be essential for the text analysis features of your web application.