T1W3 Iteration - tstorrnetnz/teaching2025 GitHub Wiki
Iteration
You should be familiar with two types of loops, for and while.
By the way, iteration means to perform something again and again.
For you to do
The problems for you to do this week can be found below and the supporting material in Chapter 7 will help you revise iteration.
I have reduced the number of questions to essential ones only.
Here are the examples that I used in teaching:
Chapter 7 Exercises
-
Write a function to count how many odd numbers are in a list.
-
Sum up all the even numbers in a list.
-
Sum up all the negative numbers in a list.
-
Count how many words in a list have length 5.
-
Sum all the elements in a list up to but not including the first even number. (Write your unit tests. What if there is no even number?)
-
Count how many words occur in a list up to and including the first occurrence of the word “sam”. (Write your unit tests for this case too. What if “sam” does not occur?)
-
Write a function, is_prime, which takes a single integer argument and returns True when the argument is a prime number and False otherwise. Add tests for cases like this:
test(is_prime(11)) test(not is_prime(35)) test(is_prime(19911121))
The last case could represent your birth date. Were you born on a prime day? In a class of 100 students, how many do you think would have prime birth dates?
-
Write a function num_even_digits(n) that counts the number of even digits in n. These tests should pass:
test(num_even_digits(123456) == 3) test(num_even_digits(2468) == 4) test(num_even_digits(1357) == 0) test(num_even_digits(0) == 1)