Day 3 of 80

Control Flow: If/Else Logic

Phase 1: Python Foundation

What You'll Build Today

Welcome to Day 3. Today is a massive turning point. Until now, your code has been a straight line—it starts at the top and runs every single line until it hits the bottom. It’s predictable, but it’s not smart.

Today, we are going to give your code a brain. We are going to teach it how to make decisions.

We will build a Mood-Based Chatbot. This program will ask the user how they are feeling, analyze their response, and choose the appropriate reply. It will even use a "digital dice roll" to pick random encouraging messages, making it feel less like a machine and more like a companion.

Here is what you will learn and why it matters:

* Booleans (True/False): Computers see the world in binary. You will learn how to reduce complex human questions into simple Yes/No answers the computer can understand.

* Comparison Operators (==, !=, <): You need to compare things. Is the user's input equal to "happy"? Is their age greater than 18? This is how we ask those questions.

* Control Flow (If/Elif/Else): This is the core logic. You will learn to create forking paths in your code so it only runs specific lines based on the situation.

* Logical Operators (and, or, not): Real life is complex. Sometimes we need to check two things at once (e.g., "If the user is happy AND it is a Tuesday").

* Libraries (import random): Why write code that someone else has already written? You will learn to open Python's "toolbox" to use pre-built code, specifically to generate random numbers.

Let's get started.

The Problem

Imagine you are building a customer service bot for a bank. You want to be polite, so you write a script that asks the user a question and then responds enthusiastically.

Here is the code you might write based on what you learned in Day 1 and 2:

# A simple conversation script

print("Welcome to BankBot AI!")

user_message = input("How can I help you today? ")

# The bot responds enthusiastically

print("That is fantastic news! I am so happy to hear that.")

print("Processing your request now...")

Now, imagine the user runs this.

Scenario A:

User: "I just got a promotion!"

Bot: "That is fantastic news! I am so happy to hear that."

Result: Perfect. Scenario B:

User: "I think my identity was stolen and I lost all my money."

Bot: "That is fantastic news! I am so happy to hear that."

Result: Disaster.

Do you feel the pain here? This code is "dumb." It treats every single input exactly the same way. It cannot adapt. It has no way of checking what the user said; it just blindly follows the script.

If we want to build AI applications, we need our code to analyze the situation and branch off in different directions. We need to say, "IF the input is bad, say sorry. OTHERWISE, say great."

There has to be a way to create these branches.

Let's Build It

We are going to build our chatbot step by step, adding intelligence layer by layer.

Step 1: The Concept of Truth (Booleans)

Before we can use if, we need to understand how Python asks questions. Python has a specific data type called a Boolean. A Boolean can only be one of two values: True or False. Note the capital T and F.

We generate these values using Comparison Operators. The most common one is == (double equals).

* = (Single equals) means Assignment. "Make this variable equal to this value."

* == (Double equals) means Comparison. "Are these two things equal?"

Run this code to see how Python answers questions:

# Assigning a variable

mood = "happy"

# Asking questions (Comparisons)

print("Is the mood happy?")

print(mood == "happy")

print("Is the mood sad?")

print(mood == "sad")

print("Is 5 greater than 3?")

print(5 > 3)

Output:
Is the mood happy?

True

Is the mood sad?

False

Is 5 greater than 3?

True

Step 2: The 'If' Statement

Now that we can generate a True or False, we can use the if statement.

The syntax is specific:

  • Write if.
  • Write the condition (the question).
  • End the line with a colon :.
  • Indent the next lines.
  • Crucial Logic: The indented lines only run if the condition is True. If it is False, Python skips them entirely.
    print("--- Chatbot v1 ---")
    

    mood = input("How are you feeling? ")

    if mood == "sad":

    print("I am sorry to hear that.")

    print("I hope your day gets better.")

    print("Conversation over.")

    Run this twice. Once type "sad", once type "happy".

    If you type "happy", the bot skips the middle part and goes straight to "Conversation over." It’s still not perfect, but it’s no longer ignoring context.

    Step 3: The 'Else' Statement

    What if the user isn't sad? We want a fallback option. In English, we say "Otherwise..." In Python, we say else.

    else does not take a condition. It catches everything that wasn't caught by the if.
    print("--- Chatbot v2 ---")
    

    mood = input("How are you feeling? ")

    if mood == "sad":

    print("I am sorry to hear that.")

    else:

    print("That sounds great! Keep it up.")

    print("Conversation over.")

    Now we handle both sides of the coin. If they are sad, we comfort them. If they are anything else (happy, angry, tired, excited), we say "That sounds great!"

    Step 4: Handling Multiple Options with 'Elif'

    The else block is a catch-all. But what if we want to handle "angry" differently than "happy"?

    We use elif (short for "else if"). You can have as many elif blocks as you want. Python checks them in order from top to bottom. As soon as it finds one that is True, it runs that block and skips the rest.

    print("--- Chatbot v3 ---")
    

    mood = input("How are you feeling? (happy/sad/angry): ")

    if mood == "sad":

    print("I am sorry to hear that.")

    elif mood == "happy":

    print("That is awesome! I love hearing good news.")

    elif mood == "angry":

    print("Take a deep breath. Count to ten.")

    else:

    # This runs if they type something we didn't expect, like "hungry"

    print("I do not understand that emotion, but I am listening.")

    Step 5: Logical Operators (And/Or)

    Sometimes a single check isn't enough.

    * and: Both conditions must be True.

    * or: At least one condition must be True.

    Let's say we want to check energy levels too.

    print("--- Chatbot v4 ---")
    

    mood = input("How are you feeling? (happy/sad): ")

    energy = input("Is your energy high or low? ")

    if mood == "happy" and energy == "high":

    print("You should go for a run!")

    elif mood == "happy" and energy == "low":

    print("You should watch a fun movie and relax.")

    elif mood == "sad" or energy == "low":

    # This runs if they are sad (regardless of energy) OR if energy is low (regardless of mood)

    print("Please take care of yourself today.")

    else:

    print("I am not sure what to recommend.")

    Step 6: Introducing Randomness (Libraries)

    Our bot is logical, but it's predictable. If I say I'm "sad" 10 times, it gives the exact same response 10 times. AI needs variety.

    Python has a standard library—a massive collection of pre-written code you can use. To use it, we import it. We will use the random library.

    We will use random.choice(), which picks one item from a list at random.

    import random  # We grab the random toolbox
    
    

    print("--- Final Chatbot ---")

    mood = input("How are you feeling? (happy/sad): ")

    if mood == "sad":

    # We create a list of possible responses using square brackets [] # We will learn more about lists later, but this is a preview

    responses = [

    "I am sorry to hear that.",

    "Sending you a virtual hug.",

    "Tomorrow is a new day.",

    "It is okay not to be okay."

    ]

    # Python picks one for us

    selected_message = random.choice(responses)

    print(selected_message)

    elif mood == "happy":

    print("That is great!")

    else:

    print("Thanks for sharing.")

    Run this code multiple times with the input "sad". You will get different answers. Your code now behaves unpredictably (in a good way).

    Now You Try

    You have the foundation. Now, stretch your skills by extending the Chatbot.

    1. The "Tired" Handler

    Add an elif statement to handle the input "tired". If the user is tired, use random.choice to suggest one of three activities: "Take a nap", "Drink some coffee", or "Go to bed early".

    2. The Number Logic

    Instead of asking for a word, ask the user: "On a scale of 1 to 10, how was your day?"

    * Remember: input() returns a string (text). You must wrap it in int() to compare numbers.

    * If the number is 8 or higher: Print "Amazing!"

    * If the number is between 4 and 7: Print "Not too bad."

    * If the number is 3 or lower: Print "I'm sorry."

    3. The Case Insensitive Fix

    Right now, if the user types "Happy" (capital H) and your code checks for "happy" (lowercase h), Python says they are not equal. True != true.

    Search online or guess: How can you convert the user's input to lowercase immediately so capitalization doesn't matter? (Hint: it involves .lower()).

    Challenge Project: The Text Adventure

    This is a classic rite of passage for new programmers. You are going to build a "Choose Your Own Adventure" game.

    The Scenario: The user is an explorer standing in front of a mysterious cave. Requirements:
  • Start: Ask the user if they want to enter the cave or run away.
  • Branching: If they enter, present them with two paths (e.g., Left or Right).
  • Nested Logic:
  • * If they go Left, they find a treasure chest. Ask if they open it.

    * If they go Right, they encounter a monster.

  • Randomness: If they fight the monster, use import random and random.randint(1, 10) to determine if they win. (e.g., If the number is > 5, they win. Else, they lose).
  • Outcomes: The game must have at least one "Game Over" ending and one "Victory" ending.
  • Example Run:
    You stand before the Cave of Wonders.
    

    Do you enter? (yes/no): yes

    You are inside. It is dark. You see a path to the Left and Right.

    Which way? (left/right): left

    You see a glowing chest. Do you open it? (yes/no): yes

    It's a trap! Game Over.

    Hints: You will need to put if statements inside* other if statements. This is called nesting. Pay very close attention to your indentation.

    * Draw a flowchart on a piece of paper before you write a single line of code. It helps immensely.

    What You Learned

    Today you moved from writing scripts to writing logic. This is the "intelligence" in Artificial Intelligence.

    * Booleans: The bedrock of logic (True / False).

    * Comparisons: ==, !=, >, <.

    * Control Flow: if, elif, else allow your code to adapt.

    * Logical Operators: and, or allow for complex decision making.

    * Libraries: import random showed you how to use external tools.

    Why This Matters for AI:

    When you eventually work with Large Language Models (LLMs), you will rarely just let the AI output whatever it wants. You will wrap it in control flow.

    IF* the user asks about a restricted topic -> Return a safety warning. IF* the AI's confidence score is low -> Ask the user for clarification. IF* the output is code -> Run a syntax checker.

    The AI provides the raw intelligence, but Control Flow provides the guardrails and the application logic.

    Tomorrow:

    Right now, if we want to ask the user a question 5 times, we have to copy-paste the code 5 times. That is messy. Tomorrow, we learn Loops—how to make the computer do the heavy lifting and repeat tasks 10, 100, or 1000 times automatically.