Introduction to Conditional Logic

SA
StudyAI Editorial
Reviewed by StudyAI tutors
· Published Updated

From the csc241\ curriculum

Introduction to Conditional Logic

TL;DR

Conditional logic lets your programs make decisions and do different things based on whether certain conditions are true or false. It's like a choose-your-own-adventure for your code, guiding its path through various possibilities. The most common way to do this is with if, elif, and else statements, which let you check conditions in a sequence.

1. The Mental Model

Imagine you're following a recipe. Sometimes it says, "If it's too thick, add more milk." Other times, it's "If using an electric mixer, beat for 3 minutes; otherwise, stir by hand for 5." Conditional logic in programming works the same way: your code checks a situation and then chooses which instructions to follow next.

2. The Core Material

Programs often need to adapt. Maybe you want to display a different message based on the time of day, or calculate a discount only if a customer spends over a certain amount. This is where conditional logic comes in.

The fundamental idea is always: "If this is true, then do that."

In Python, the primary tools for conditional logic are if, elif, and else statements.

The if Statement

Inspirational quote 'And That's The Way It Is' on pink Scrabble tiles.
Photo by Anna Tarazevich on Pexels

The if statement is the simplest form. It checks a condition, and if that condition is true, it executes a block of code.

temperature = 25

if temperature > 20:
    print("It's a warm day!")

In this example, temperature > 20 is the condition. Since 25 is greater than 20, the condition is True, and the print() statement runs. If temperature were 15, the condition would be False, and nothing would be printed.

Notice the colon : after the condition and the indentation of the print() line. Indentation is crucial in Python; it defines the block of code that belongs to the if statement.

The else Statement

Vintage typewriter displaying Oscar Wilde's quote 'Be yourself, everyone else is already taken.'
Photo by Matej on Pexels

What if you want to do something when the condition is False? That's where else comes in. It provides an alternative block of code to run.

age = 17

if age >= 18:
    print("You are an adult.")
else:
    print("You are not yet an adult.")

Here, since age (17) is not greater than or equal to 18, the if condition is False. So, the else block executes, and "You are not yet an adult." is printed.

The elif Statement (Else If)

Luxurious wedding setting with white roses, candles, and personalized glass bottle.
Photo by Betül Üstün on Pexels

Sometimes you have more than two possibilities. You might need to check a series of conditions. That's elif's job. It stands for "else if" and lets you check another condition if the previous if or elif conditions were False.

You can have multiple elif statements between an if and an optional else. The conditions are checked in order. As soon as one condition is True, its block of code executes, and the rest of the elif/else chain is skipped.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

In this example:
1. score >= 90 is False (85 is not >= 90).
2. score >= 80 is True (85 is >= 80). So, "Grade: B" is printed, and the rest of the checks (elif score >= 70 and else) are skipped.

This sequence of checks is like a decision tree:

graph TD
    A["Check if Score >= 90?"] -->|True| B["Print: Grade A"]
    A -->|False| C["Check if Score >= 80?"]
    C -->|True| D["Print: Grade B"]
    C -->|False| E["Check if Score >= 70?"]
    E -->|True| F["Print: Grade C"]
    E -->|False| G["Print: Grade F"]

Combining Conditions

A creative arrangement of colorful clothespins on bright red and blue backgrounds.
Photo by Valentin Ivantsov on Pexels

You can use logical operators (and, or, not) to create more complex conditions.

  • and: Both conditions must be True.
  • or: At least one condition must be True.
  • not: Reverses the truth value of a condition.
hour = 14 # 2 PM
is_weekend = False

if hour >= 9 and hour <= 17 and not is_weekend:
    print("It's working hours on a weekday.")
elif is_weekend:
    print("Enjoy your weekend!")
else:
    print("It's not working hours.")

In this example, the first if condition is True because hour >= 9 is True, hour <= 17 is True, and not is_weekend (which is not False) is True. All parts with and are True, so "It's working hours on a weekday." is printed.

3. Worked Example

Let's write a simple program that asks a user for their favorite color and then gives a different response based on what they type.

# 1. Get input from the user
fav_color = input("What's your favorite color? ")

# 2. Convert input to lowercase to make checking easier (e.g., "Red" or "red")
fav_color = fav_color.lower()

# 3. Use conditional logic to respond
if fav_color == "blue":
    print("Ah, blue! A classic and calming choice.")
elif fav_color == "green":
    print("Green is great! Nature's color.")
elif fav_color == "red":
    print("Bold choice! Red means energy.")
elif fav_color == "yellow" or fav_color == "gold": # Combining conditions
    print("Sunshine and happiness! Love yellow.")
else:
    print(f"I see, '{fav_color}' is a nice color.")
    print("That's an interesting favorite!")

If you run this:
- If you type Blue, it'll print "Ah, blue! A classic and calming choice."
- If you type green, it'll print "Green is great! Nature's color."
- If you type Gold, it'll print "Sunshine and happiness! Love yellow."
- If you type purple, it'll print multiline text: "I see, 'purple' is a nice color. That's an interesting favorite!"

4. Key Takeaways

  • Conditional logic allows your program to make decisions and execute different code paths.
  • The if statement runs a code block only if its condition is true.
  • The else statement provides an alternative code block to run if the if (and any elif) conditions are false.
  • The elif statement lets you check additional conditions in sequence when previous ones were false.
  • Conditions are typically built using comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not).
  • The first if or elif condition that evaluates to True will execute its block, and the rest of the chain is skipped.
  • Indentation is how Python knows which lines of code belong to each if, elif, or else block.

Common Mistakes to Avoid:
- Forgetting the colon : after if, elif, or else statements.
- Incorrect indentation: This is a big one in Python and will cause IndentationErrors or unexpected program behavior.
- Using = instead of == for comparison: = is for assignment, == is for checking equality.
- Not thinking about order for elif: The order matters, especially for ranges (e.g., check score >= 90 before score >= 80).

5. Now Try It

Write a small program that asks the user for a number. Based on the number, print one of these messages:
- "That's a positive number!" if it's greater than zero.
- "That's zero!" if it's exactly zero.
- "That's a negative number." if it's less than zero.

What success looks like: Your program should correctly classify any integer the user types (e.g., 5, 0, -3) and print the appropriate message.

Frequently asked about Introduction to Conditional Logic

# Introduction to Conditional Logic ## TL;DR Conditional logic lets your programs make decisions and do different things based on whether certain conditions are true or false. It's like a choose-your-own-adventure for your code, guiding its path through various possibilities. Read the full notes above.

Introduction to Conditional Logic is a core topic in csc241\. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes. Every note in the StudyAI Campus Hub is free to read. Create a free account if you want to clone the full plan, generate your own notes from your textbook, or get AI-powered practice quizzes and flashcards.

Get the full csc241\ curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Create Free Account