Comparison Operators and Basic 'if' Statements

SA
StudyAI
AI-generated study notes
· Published Updated

From the csc241\ curriculum

TL;DR

Comparison operators let your code ask questions like "is this equal to that?", resulting in a True or False answer. You use these True/False results with if statements to make decisions and run different parts of your code based on conditions. This allows your programs to be dynamic and respond to varying inputs or situations.

1. The Mental Model

Think of comparison operators as asking a "yes" or "no" question about two values. An if statement then uses that "yes" (True) or "no" (False) answer to decide which path of code to follow. It's like a fork in the road for your program.

2. The Core Material

What are Comparison Operators?

Comparison of two smartphones showing Realme UI and Xiaomi HyperOS interfaces on their screens.
Photo by Andrey Matveev on Pexels

Comparison operators compare two values and always return either True or False. These are special boolean values in Python.

Here are the main ones:

  • == (Equal to): Checks if two values are the same. Note the double equals sign! A single = is for assignment.
  • != (Not equal to): Checks if two values are different.
  • > (Greater than): Checks if the left value is larger than the right.
  • < (Less than): Checks if the left value is smaller than the right.
  • >= (Greater than or equal to): Checks if the left value is larger than or the same as the right.
  • <= (Less than or equal to): Checks if the left value is smaller than or the same as the right.
x = 10
y = 5

print(x == y)   # False
print(x != y)   # True
print(x > y)    # True
print(x <= y)   # False

Basic 'if' Statements

Mathematical study scene with open book, graph paper, and pen for learning and homework.
Photo by Lum3n on Pexels

An if statement allows your program to execute a block of code only if a certain condition is True. If the condition is False, that block of code is skipped.

The basic structure is:

if condition:
    # Code to execute if 'condition' is True
    # This block must be indented!

The condition is usually an expression involving comparison operators.

Adding 'else'

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

You can extend an if statement with an else block. The else block executes if the if condition is False.

if condition:
    # Code if condition is True
else:
    # Code if condition is False

Adding 'elif' (else if)

A close-up of Arabic calligraphy drawn on textured paper with marbled patterns.
Photo by betül nur akyürek on Pexels

For more complex decisions with multiple possible conditions, you use elif. This checks additional conditions if the previous if or elif conditions were False. You can have multiple elif blocks.

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition1 is False, but condition2 is True
elif condition3:
    # Code if condition1 and condition2 are False, but condition3 is True
else:
    # Code if all above conditions are False

Here's how an if-elif-else decision path looks:

graph TD
    A["Start"] --> B{{"Is condition1 True?"}};
    B -- "Yes" --> C["Execute Code Block 1"];
    B -- "No" --> D{{"Is condition2 True?"}};
    D -- "Yes" --> E["Execute Code Block 2"];
    D -- "No" --> F{{"Is condition3 True?"}};
    F -- "Yes" --> G["Execute Code Block 3"];
    F -- "No" --> H["Execute Else Block"];
    C --> I["End"];
    E --> I;
    G --> I;
    H --> I;

3. Worked Example

Let's write a program that checks a student's score and prints their grade.

score = 85 # You can change this value to test different outcomes

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

print("Grading complete.")

If score is 85:
1. score >= 90 (85 >= 90) is False.
2. score >= 80 (85 >= 80) is True.
3. The code print("Grade: B") executes.
4. The rest of the elif and else blocks are skipped.
5. print("Grading complete.") executes.

Output:

Grade: B
Grading complete.

4. Key Takeaways

  • Comparison operators (==, !=, >, <, >=, <=) evaluate to either True or False.
  • if statements use these True/False results to decide which code block to run.
  • The code block following if, elif, or else must be indented.
  • elif allows you to check multiple conditions in sequence.
  • else provides a fallback block of code if none of the preceding if or elif conditions were True.
  • Only one block (if, one elif, or else) will execute within an if-elif-else structure.
  • The order of elif conditions matters because they are checked sequentially.

Common Mistakes to Avoid

  • Using = (assignment) instead of == (comparison) in an if condition. This often leads to errors or unexpected behavior.
  • Forgetting to indent the code blocks under if, elif, or else. Python uses indentation to define code blocks.
  • Placing the else or elif block in the wrong order or without a preceding if.
  • Not considering the order of elif conditions, which can lead to a less specific condition being met before a more specific one.

5. Now Try It

Write a Python program that asks the user for their age using input(). Then, use if-elif-else statements with comparison operators to print one of the following messages: "You are a child.", "You are a teenager.", "You are an adult.", or "You are a senior citizen.". Define the age ranges as you see fit (e.g., child < 13, teenager 13-19, etc.).

Success looks like: Your program correctly categorizes ages (e.g., 10 prints "You are a child.", 16 prints "You are a teenager.", 30 prints "You are an adult.", 75 prints "You are a senior citizen.").

Frequently asked about Comparison Operators and Basic 'if' Statements

Comparison operators let your code ask questions like "is this equal to that?", resulting in a True or False answer. You use these True/False results with if statements to make decisions and run different parts of your code based on conditions. Read the full notes above for the details.

Comparison Operators and Basic 'if' Statements 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 in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Complex Control Flow with 'elif' and 'else'

More from csc241\


Get the full csc241\ curriculum

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

Save this course free