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.
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
- Python evaluates the if condition first.
- If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
- If none is True, the else branch runs.
- 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.
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.
The Three-Step Filter
- 1The for statement retrieves one dictionary key.
- 2The index operator retrieves the value associated with that key.
- 3The if statement compares the retrieved value with the threshold or other condition.
counts = {'Ana': 14, 'Bo': 7, 'Chuck': 1, 'Dina': 18}
for name in counts:
if counts[name] > 10:
print(name, counts[name])- 1The loop first retrieves the key Ana. The expression counts[name] retrieves 14, and 14 is greater than 10, so the print statement runs.
- 2The loop then retrieves Bo. Its value is 7, so the condition is false and the print statement is skipped.
- 3The loop retrieves Chuck. Its value is 1, so this entry is also skipped.
- 4Finally, Dina has the value 18. The condition is true, so Dina and 18 are printed.
Ana 14
Dina 18Storing 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.
{'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.
| Operation | What happens | Typical result |
|---|---|---|
| Filtering | Select entries whose values satisfy a condition | A new dictionary or list containing selected entries |
| Transforming | Modify entries that have been selected | Entries with changed contents |
Filtering decides which entries belong in the result; transforming changes selected entries.
Nested Branches
A nested conditional is a conditional statement placed inside another conditional statement, usually inside one of the outer conditional's branches.
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')- 1Python evaluates the outer condition x == y first.
- 2Because 3 == 5 is false, Python skips the first outer branch and enters the else branch.
- 3The else branch contains the nested conditional, so Python evaluates x < y.
- 4Because 3 < 5 is true, the inner if branch runs and prints x is less than y.
- 5The inner else branch does not run.
x is less than yOnly 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 likeif name > 10:Why it failsThe loop variable is a key. In the described pattern, the condition is supposed to test the value associated with that key.
Do this insteadUse the index operator to retrieve the value: if counts[name] > 10:
Common mistake Using assignment where a comparison is required
What it looks likeif x = y:Why it failsThe conditional needs to test whether two values are equal.
Do this insteadUse the comparison operator: if x == y:
Common mistake Modifying the dictionary being iterated through
Why it failsChanging the dictionary during iteration is identified as a common mistake in this filtering pattern.
Do this insteadCollect passing entries in a separate dictionary such as filtered.
Common mistake Assuming the nested conditional always runs
Why it failsAn inner conditional runs only when execution enters the outer branch that contains it.
Do this insteadTrace the outer condition first, then decide whether the inner condition is reached.
Trace and Practice
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.
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
- 1A for loop over a dictionary supplies keys, so filtering by value requires an index lookup such as counts[key].
- 2The if statement decides whether the current entry passes the filter; rejected entries are skipped.
- 3Filtered entries can be printed immediately or collected in a separate dictionary for later use.
- 4Filtering selects entries, while transforming modifies selected entries.
- 5A 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.