Control Flow By the CodeCracker Team

Conditions and if / else Explained for Beginners

Learn how computer programs make decisions using boolean expressions, comparison operators, and single, two-way, and multi-branch if / else structures in blocks, Python, and C++.

In This Article

  • Write clear boolean conditions using the six standard comparison operators.
  • Structure single-branch (if), two-branch (if/else), and multi-branch (elif / else if) decisions.
  • Understand why order matters when chaining multiple conditions from top to bottom.
  • Avoid the classic '=' assignment vs '==' equality comparison bug.

How Programs Make Decisions

A program that only runs straight from top to bottom is like a train on a single track without switches: it does the exact same thing every time it runs, regardless of user input. Real software needs to react to changing data—checking whether a password is correct, whether an item is in stock, or whether a game character has enough health to survive a hit.

In computer science, decision-making is called conditional branching (or selection). At every fork in the road, the computer asks a yes-or-no question called a boolean condition. Depending on whether the answer is true or false, the program takes one path and completely skips the other.

Key Idea: A condition never evaluates to "maybe." Every condition inside an if statement must simplify to a single boolean value: True or False.

The Six Comparison Operators

To build a boolean question that compares two numbers or values, visual blocks, Python, and C++ all use the same six relational operators:

  • == Equal to: True if both sides have the exact same value (e.g., lives == 0).
  • != Not equal to: True if the two sides differ (e.g., status != "locked").
  • < Less than: True if the left value is strictly smaller than the right value (e.g., temp < 0).
  • > Greater than: True if the left value is strictly larger than the right value (e.g., score > 100).
  • <= Less than or equal to: True if the left value is smaller than or equal to the right value.
  • >= Greater than or equal to: True if the left value is larger than or equal to the right value.

The Classic Bug: Single Equals (=) vs. Double Equals (==)

In everyday math class, the single equals sign = means "is equal to." In programming, however, a single equals sign is the assignment operator—it means "store the value on the right inside the variable box on the left."

  • x = 10 puts the number 10 into x.
  • x == 10 asks the question: "Does x currently hold the number 10?"

In Python, accidentally writing if x = 10: causes a SyntaxError right away, protecting you from the mistake. In C++, however, writing if (x = 10) is actually legal syntax: it overwrites x with 10 and treats any non-zero number as true, causing your if branch to run every single time! Visual blocks prevent this bug because setting a variable and comparing two values are two completely different blocks.

Three Ways to Branch: Single, Two-Way, and Multi-Branch

1. Single-Branch if (Do Something Optional)

A standalone if block checks a condition. If it is true, the indented code runs. If it is false, the program does nothing special and moves on to the next line below the block. For example, applying rain gear only when it is raining.

2. Two-Way if / else (Either-Or Choice)

When you attach an else branch, you guarantee that exactly one of the two paths will run. It is impossible for both branches to execute, and it is impossible for neither to execute. The else branch never takes its own condition—it acts as the automatic fallback whenever the if condition is false.

3. Multi-Branch if / elif / else (Multiple Mutually Exclusive Tiers)

What if you have three, four, or five possible outcomes, such as assigning letter grades (A, B, C, F) or shipping rates by package weight? You chain conditions together using else if (spelled elif in Python and else if in C++).

Visual Block Logic

SET score TO 84
IF score >= 90 DO
  SET grade TO "A"
ELSE IF score >= 80 DO
  SET grade TO "B"
ELSE IF score >= 70 DO
  SET grade TO "C"
ELSE
  SET grade TO "F"
PRINT grade

Python

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

C++

int score = 84;
std::string grade;
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else {
    grade = "F";
}
std::cout << grade << "
";

Why Condition Order Matters in Multi-Branch Chains

In an if / elif / else chain, the computer tests conditions strictly from top to bottom and stops at the very first branch that evaluates to true. Once a matching branch executes, all remaining elif and else branches below it are skipped, even if their conditions are also true!

In our grading example above, score is 84:

  1. First, the program checks 84 >= 90. That is False, so it moves to the next branch.
  2. Second, it checks 84 >= 80. That is True! It sets grade = "B" and immediately jumps to the end of the entire structure.
  3. Even though 84 >= 70 is also mathematically true, that third branch is never even tested because the second branch already won.
Key Idea: Always order chained conditions from most specific (or highest threshold) to least specific. If you put if score >= 70 at the very top, a student with a 95 would match the first branch and receive a "C"!

Combining Conditions with Logical Operators (AND, OR, NOT)

Sometimes a single comparison is not enough. You can join two boolean comparisons using logical operators:

  • AND (and in Python, && in C++): True only if both sides are true. Example: age >= 16 and has_permit == True.
  • OR (or in Python, || in C++): True if at least one side is true. Example: day == "Saturday" or day == "Sunday".
  • NOT (not in Python, ! in C++): Flips True to False and False to True.

Nested Conditionals vs. Compound Conditions

In visual blocks, you can place one if block inside the mouth of another if block—a structure called a nested conditional. For instance, an outer if might check whether a user's account is active, and an inner if might check whether their subscription tier is "Pro." Both checks must pass for the inner action to run.

While nesting two levels deep is easy to read when you want an else message specific to each check (such as printing "Account inactive" versus "Upgrade to Pro"), nesting three or four if blocks inside each other creates deeply indented "arrow code" that is hard to follow. Whenever you only care about the case where two conditions are simultaneously true, flatten the nested blocks into a single compound condition using and (in Python) or && (in C++): if is_active and is_pro:. Keeping your decision trees flat and well-ordered makes your logic much easier to test and maintain.

Try It Yourself

Spot the Ordering Bug: A theme park charges $10 for children under 12, $15 for seniors aged 65 and up, and $25 for regular adults. A beginner writes the following Python logic:

age = 70
if age >= 12:
    price = 25
elif age >= 65:
    price = 15
else:
    price = 10
print(price)

Questions:

  1. What price does this program print for a 70-year-old visitor, and why?
  2. How can you reorder the conditions so that children, adults, and seniors all get the correct ticket price?

Answer: (1) It prints 25 because 70 >= 12 is checked first and evaluates to True, skipping the elif age >= 65 branch completely. (2) Check if age >= 65: first, then elif age >= 12:, then else:.