7e. Review: Loops with Decisions#
More practice after Chapter 7: Iteration and Search. These questions practise the pattern at the heart of this page: a for loop with a decision inside it. Sometimes the decision is one if; sometimes it is a chain of elifs; sometimes it is an if inside another if. In every question, work out which branch a value takes before you write the code.
Try each question first, then open its Answer.
Practice questions#
Question 1 (easy): write a function#
Write a function called count_evens that takes n and returns how many even numbers are in range(n), starting at 0.
For example, count_evens(10) is 5 (0, 2, 4, 6, 8). count_evens(1) is 1 (just 0 — is 0 even? Yes, 0 % 2 is 0).
Start from this header (replace ... with the body):
def count_evens(n):
...
Answer
def count_evens(n):
count = 0
for i in range(n):
if i % 2 == 0:
count += 1
return count
Question 2 (easy): write a function#
Write a function called sum_evens that takes n and returns the sum of the even numbers from 0 through n.
For example, sum_evens(10) is 30 (0 + 2 + 4 + 6 + 8 + 10).
Start from this header (replace ... with the body):
def sum_evens(n):
...
Answer
def sum_evens(n):
total = 0
for i in range(n+1):
if i % 2 == 0:
total += i
return total
This is the same shape as Question 1, with total += i inside the if.
Question 3 (medium): write a function#
Write a function called fizzbuzz that prints, one per line, for 1 through n: 'FizzBuzz' for a number divisible by both 3 and 5, 'Fizz' for a number divisible by 3 only, 'Buzz' for a number divisible by 5 only, and the number itself otherwise.
For example, fizzbuzz(15) ends with ..., 13, 14, FizzBuzz (each on its own line).
Question to think about first: what goes wrong if you test divisibility by 3 before you test divisibility by both?
Start from this header (replace ... with the body):
def fizzbuzz(n):
...
Answer
def fizzbuzz(n):
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Test both first, then 3, then 5, then else. This version prints instead of building a list, because lists are not taught until Chapter 9.
Question 4 (easy): write a function#
Write a function called count_vowels that takes a word and returns how many letters in the word are vowels.
For example, count_vowels('Hello World') is 3.
Start from this header (replace ... with the body):
def count_vowels(word):
...
Answer
def count_vowels(word):
count = 0
for ch in word:
if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U':
count += 1
return count
Chapter 7 has not yet taught using in to test whether a character is in a string, so this answer spells the vowel test out with or instead.
Question 5 (medium): write a function#
Write a function called describe_number that takes n and returns 'positive even', 'positive odd', 'negative even', 'negative odd', or 'zero'.
For example, describe_number(4) is 'positive even'; describe_number(-3) is 'negative odd'; describe_number(0) is 'zero'.
Start from this header (replace ... with the body):
def describe_number(n):
...
Answer
def describe_number(n):
if n > 0:
if n % 2 == 0:
return 'positive even'
else:
return 'positive odd'
elif n < 0:
if n % 2 == 0:
return 'negative even'
else:
return 'negative odd'
else:
return 'zero'
An outer if/elif/else on the sign, with an inner if/else on evenness inside the positive and negative branches. Zero must be handled separately from evenness — otherwise 0 would be called ‘positive even’.
Question 6 (medium): write a function#
Write a function called count_even_and_div3 that takes n and returns how many numbers from 0 through n are even AND divisible by 3.
For example, count_even_and_div3(20) is 4 (0, 6, 12, 18).
Start from this header (replace ... with the body):
def count_even_and_div3(n):
...
Answer
def count_even_and_div3(n):
count = 0
for i in range(n+1):
if i % 2 == 0:
if i % 3 == 0:
count += 1
return count
Outer if i % 2 == 0:, inner if i % 3 == 0:, count inside both. Also correct, and worth comparing: a single if with and. The nested version makes the two decisions visible, one at a time.
Question 7 (medium): write a function#
Write a function called classify_letters that takes a string s and prints, each on its own line, how many vowels, how many consonants, and how many other characters are in s.
For example, classify_letters('Hi! 123') prints:
1
1
5
Start from this header (replace ... with the body):
def classify_letters(s):
...
Answer
def classify_letters(s):
vowels = 0
consonants = 0
other = 0
for ch in s:
if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U':
vowels += 1
elif ('a' <= ch <= 'z') or ('A' <= ch <= 'Z'):
consonants += 1
else:
other += 1
print(vowels)
print(consonants)
print(other)
This version prints the three counts instead of returning them together: returning several values at once would need tuples, which are not taught until Chapter 11. Order matters: vowels must be tested before consonants, or every vowel would be counted as a consonant.
Question 8 (hard): write a function#
Write a function called first_even_over that takes n and limit and returns the first even number from n through limit, or None if there is none.
For example, first_even_over(7, 20) is 8; first_even_over(7, 7) is None.
Start from this header (replace ... with the body):
def first_even_over(n, limit):
...
Answer
def first_even_over(n, limit):
for i in range(n, limit+1):
if i % 2 == 0:
return i
return None
The return inside the loop is the search pattern from Chapter 7: the first value that passes the test ends the search.
Credits#
More review questions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International