Skip to content

A4 - Introduction to for .. in Loops

Consider this code:

for month in ["January", "February", "March", "April"]:
    print(month)

It will print:

January
February
March
April

In the above example, the print statement runs four times, once for every list item. Each time through the loop, the month variable takes on the value of one of the list items, going from beginning to end.

Here's another example:

nums = [3, 11, 30, 8, 2, 25, 32]
for num in nums:
    if num > 10:
        print(num)

It will print:

11
30
25
32

Again, this loop iterates once for each list item, and the variable num will take on the value of one of the list items on each iteration. This time, however, the body of the loop contains an if statement causing only the numbers greater than 10 to be printed.

Your Task

Complete this task in a file called a4.py.

Part 1

Copy the code from the second example into your file. Here it is again:

nums = [3, 11, 30, 8, 2, 25, 32]
for num in nums:
    if num > 10:
        print(num)

Change the condition of the if statement so that a different subset of the list is printed.

Part 2

Under part 1, create a list of five different types of strings. For example, something like this:

strings = ["donut", "Robert", "me@example.com", "99%", "Hi there!"]
(you can use this list or create your own)

Using a similar technique to part 1, create a for loop containing an if statement that will print only some of the strings according to a condition you choose. Use one or more of the string methods we've been using in this unit.

Optional Extension

There's lots of variations of things you can do inside these type of loops. For example, consider the following:

nums = [3, 11, 30, 8, 2, 25, 32]
for num in nums:
    if num > 10:
        print(f"{num} is greater than 10, and the last digit of the number is {num%10}")
    else:
        print(f"{num} is less than or equal to 10, and the last digit of the number is {num%10}")

What unique variation could you come up with? Feel free to use a previous example as a starting point, or start from scratch!