Day 2 — Solutions

Control flow, loops, lists, tuples, sets


Exercise 1 — Nested conditionals

is_registered = True
at_correct_precinct = False

if is_registered:
    if at_correct_precinct:
        print("Allow to vote")
    else:
        print("Redirect to correct precinct")
else:
    print("Provisional ballot")
Redirect to correct precinct

Alternative using a single chain of conditions:

if is_registered and at_correct_precinct:
    print("Allow to vote")
elif is_registered:
    print("Redirect to correct precinct")
else:
    print("Provisional ballot")

Exercise 2 — for loop with a list

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]

# Part 1
for name in presidents:
    print(f"President {name}")

# Part 2
count = 1
for name in presidents:
    print(f"#{count}: {name}")
    count += 1
President Washington
President Adams
President Jefferson
President Madison
President Monroe
#1: Washington
#2: Adams
#3: Jefferson
#4: Madison
#5: Monroe

Exercise 3 — while loop with a condition

n = 101
while not (n % 7 == 0 and n % 11 == 0):
    n += 1
print(n)  # 154
154

7 * 11 = 77, so any multiple of both is a multiple of 77. The first one above 100 is 154.


Exercise 4 — Nested while loops

year = 2020
while year <= 2030:
    count = 0
    y = year
    while y % 4 != 0:
        count += 1
        y += 1
    print(f"{year} reaches a presidential election year ({y}) in {count} years.")
    year += 1
2020 reaches a presidential election year (2020) in 0 years.
2021 reaches a presidential election year (2024) in 3 years.
2022 reaches a presidential election year (2024) in 2 years.
2023 reaches a presidential election year (2024) in 1 years.
2024 reaches a presidential election year (2024) in 0 years.
2025 reaches a presidential election year (2028) in 3 years.
2026 reaches a presidential election year (2028) in 2 years.
2027 reaches a presidential election year (2028) in 1 years.
2028 reaches a presidential election year (2028) in 0 years.
2029 reaches a presidential election year (2032) in 3 years.
2030 reaches a presidential election year (2032) in 2 years.

Same pattern as the multiples-of-13 example from the slides, the outer loop walks through values, inner loop performs a counting computation per value. Years already divisible by 4 (2020, 2024, 2028) print 0 years because the inner loop’s condition (y % 4 != 0) is False before any iteration. Note y = year and count = 0 reset inside the outer loop so each year starts fresh.


Exercise 5 — List operations

states = ["Ohio", "Florida", "Pennsylvania", "Wisconsin", "Michigan"]

states.append("Arizona")
states.insert(2, "Georgia")
states.remove("Florida")
states.sort()

print(states)
print(len(states))
['Arizona', 'Georgia', 'Michigan', 'Ohio', 'Pennsylvania', 'Wisconsin']
6

append adds to the end, insert adds at a position, remove deletes by value, sort reorders in place.


Exercise 6 — Iterating over two lists

senators = ["Sanders", "Warren", "Cruz", "Cornyn", "Schumer"]
years = [34, 12, 13, 23, 26]

for i in range(len(senators)):
    if years[i] > 15:
        print(f"{senators[i]}: {years[i]} years")
Sanders: 34 years
Cornyn: 23 years
Schumer: 26 years

range(len(senators)) produces indices 0, 1, 2, ... up to len(senators) - 1. We then access each list with [i]. This works, but it’s clunky. Tomorrow we’ll see zip(), which produces matched pairs directly, plus a one-line version using a list comprehension.


Exercise 7 — Sets

bill_a_sponsors = ["Sanders", "Warren", "Klobuchar", "Booker", "Brown"]
bill_b_sponsors = ["Warren", "Booker", "Markey", "Whitehouse", "Klobuchar"]

a = set(bill_a_sponsors)
b = set(bill_b_sponsors)

print("Both:", a.intersection(b))
print("A only:", a.difference(b))
print("Total unique:", len(a.union(b)))
Both: {'Booker', 'Warren', 'Klobuchar'}
A only: {'Sanders', 'Brown'}
Total unique: 7

Once you’ve converted both lists to sets, use set methods .intersection() returns elements in both, .difference() returns elements in the first but not the second, and .union() returns all elements combined (with duplicates removed).

Exercise 8 — Putting it together

vote_counts = [4250, 3980, -1, 5120, 2890, -1, 6400, 4100]

total = 0
valid_count = 0
missing_count = 0

for v in vote_counts:
    if v == -1:
        missing_count += 1
    else:
        total += v
        valid_count += 1

mean = round(total / valid_count, 1)
print(f"Mean: {mean} ({missing_count} missing values dropped)")
Mean: 4456.7 (2 missing values dropped)

Tracking three counters in one pass is the common pattern. Tomorrow we’ll see how numpy and pandas handle missing values more gracefully (NaN).