Concepts / Writing Conditional Statements

Writing Conditional Statements

A for loop over a dictionary iterates through keys; to filter by value, use the index operator to retrieve each value and test it against a condition.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Selecting Entries by Value

Suppose a dictionary records how many times each name appears in a dataset. You want only the names whose counts are greater than 10. The important question is not merely how to write an if statement. It is how to connect that condition to the value belonging to the current dictionary key.

When a for loop iterates through a dictionary, Python gives the loop one key at a time. If the condition concerns the corresponding value, retrieve that value with the index operator before testing it. The general pattern is: iterate through a key, look up its value, and let an if statement decide whether the entry should be selected.

countsdictionarynamecurrent keyvalue > 10test the valuecounts[name]corresponding valueloop retrievesindex lookupcompare
How does the loop move from each dictionary key to its corresponding value so it can test the value against a condition?

The Three-Step Filter

  1. 1
    The for statement retrieves one dictionary key.
  2. 2
    The index operator retrieves the value associated with that key.
  3. 3
    The if statement compares the retrieved value with the threshold or other condition.
Code walkthrough
counts = {'Ana': 14, 'Bo': 7, 'Chuck': 1, 'Dina': 18}

for name in counts:
    if counts[name] > 10:
        print(name, counts[name])
  1. 1
    The loop first retrieves the key Ana. The expression counts[name] retrieves 14, and 14 is greater than 10, so the print statement runs.
  2. 2
    The loop then retrieves Bo. Its value is 7, so the condition is false and the print statement is skipped.
  3. 3
    The loop retrieves Chuck. Its value is 1, so this entry is also skipped.
  4. 4
    Finally, Dina has the value 18. The condition is true, so Dina and 18 are printed.
Output
Ana 14
Dina 18
dictionary entrykey and valuevalue > 10conditionfilterednew dictionarynext entrynot selectedinspecttruefalse
How does each dictionary entry that passes the condition move into a new result while rejected entries are left out?

Storing the Filtered Result

Printing a passing entry is useful when inspecting a result immediately. If the selected entries will be used later, place them in a new dictionary instead. The condition remains the same; only the action taken when the condition is true changes.

python
Output (expected)
{'Ana': 14, 'Dina': 18}

This loop does not alter the entries in counts. It selects qualifying key-value pairs and places them in filtered. After the loop, filtered contains only entries whose values exceeded 10. That new dictionary can be passed to other functions, iterated through again, or modified further.

OperationWhat happensTypical result
FilteringSelect entries whose values satisfy a conditionA new dictionary or list containing selected entries
TransformingModify entries that have been selectedEntries with changed contents

Filtering decides which entries belong in the result; transforming changes selected entries.

Filteringselect qualifying entriesfilteredselected entriesTransformingmodify selected entriesmodified resultchanged entrieskeepmodify
What is the difference between selecting only entries that meet a condition and modifying the entries that are selected?

Nested Branches

Definition

A nested conditional is a conditional statement placed inside another conditional statement, usually inside one of the outer conditional's branches.

Code walkthrough
x = 3
y = 5

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')
  1. 1
    Python evaluates the outer condition x == y first.
  2. 2
    Because 3 == 5 is false, Python skips the first outer branch and enters the else branch.
  3. 3
    The else branch contains the nested conditional, so Python evaluates x < y.
  4. 4
    Because 3 < 5 is true, the inner if branch runs and prints x is less than y.
  5. 5
    The inner else branch does not run.
Output
x is less than y
x == youter conditionequal messageouter trueless messageinner truex < yinner conditiongreater messageinner falsetruefalsetruefalse
What happens next when the outer condition is true or false, and which inner condition branches execute?

Only one complete path executes. Python evaluates the outer condition first. If the selected outer branch contains the inner conditional, Python evaluates the inner condition next. If the other outer branch is selected, the inner conditional is never evaluated.

Indentation and Readability

Indentation shows which statements belong to each conditional block. In a nested structure, the inner if statement is indented farther than the outer if statement, and statements inside the inner branches are indented farther again. Reading the indentation lets you identify which branch controls each action.

  • Common mistake

    Comparing the dictionary key instead of its value

    What it looks like
    if name > 10:
    Why it fails

    The loop variable is a key. In the described pattern, the condition is supposed to test the value associated with that key.

    Do this instead

    Use the index operator to retrieve the value: if counts[name] > 10:

  • Common mistake

    Using assignment where a comparison is required

    What it looks like
    if x = y:
    Why it fails

    The conditional needs to test whether two values are equal.

    Do this instead

    Use the comparison operator: if x == y:

  • Common mistake

    Modifying the dictionary being iterated through

    Why it fails

    Changing the dictionary during iteration is identified as a common mistake in this filtering pattern.

    Do this instead

    Collect passing entries in a separate dictionary such as filtered.

  • Common mistake

    Assuming the nested conditional always runs

    Why it fails

    An inner conditional runs only when execution enters the outer branch that contains it.

    Do this instead

    Trace the outer condition first, then decide whether the inner condition is reached.

Trace and Practice

EASY

Create a new dictionary named frequent containing only the entries from counts whose values are greater than 10. Then explain, in order, what happens for each key as the loop runs.

Hints
  • Start with an empty dictionary for the result.
  • Iterate through counts so the loop receives keys.
  • Use the index operator to retrieve the value for the current key.
  • Add the current key and value to the new dictionary only when the condition is true.
MEDIUM

Trace this nested conditional for x = 8 and y = 8. Which message runs? Next, trace it for x = 8 and y = 11. Identify the outer branch and, when reached, the inner branch.

Hints
  • Evaluate x == y before considering x < y.
  • The inner condition is inside the outer else branch.
  • Only one complete path executes for each pair of values.

Key Takeaways

  1. 1
    A for loop over a dictionary supplies keys, so filtering by value requires an index lookup such as counts[key].
  2. 2
    The if statement decides whether the current entry passes the filter; rejected entries are skipped.
  3. 3
    Filtered entries can be printed immediately or collected in a separate dictionary for later use.
  4. 4
    Filtering selects entries, while transforming modifies selected entries.
  5. 5
    A nested conditional runs only when execution reaches the branch that contains it, and excessive nesting can make code difficult to read.

At a glance

  • Dictionary iteration gives the loop keys, not values.
  • Use the index operator to retrieve the current value before testing it.
  • Store passing entries in a new dictionary when they are needed later.
  • Trace nested conditionals from the outer condition to the reachable inner branch.
  • Avoid unnecessary nesting when clearer logical operators can express the same decision.

Related concepts

More concepts starting with W