Loops
For Loop
We can loop over a list in Python using a for loop:
>>> fruits = ["strawberries", "bananas", "apples", "oranges"]
>>>
>>> for fruit in fruits:
... print(fruit)
...
strawberries
bananas
apples
oranges
Here, fruit is a variable name which will contain a different item in each iteration of the loop.
We can use any name we like for this variable:
>>> for x in fruits:
... print(x)
...
strawberries
bananas
apples
oranges
We can also loop over an individual string:
>>> fruit = "apples"
>>> for letter in fruit:
... print(letter)
...
a
p
p
l
e
s
Building Up A List
Here’s a for loop that loops over one list of numbers and converts each number to a string:
>>> numbers = [2, 1, 3, 4, 7, 11]
>>> strings = []
>>> for n in numbers:
... strings.append(str(n))
...
>>> strings
['2', '1', '3', '4', '7', '11']
Iterables
What else do you think you could loop over in Python?
Lists (as we saw)
Tuples
Strings
An iterable is anything that you can loop over and anything that you can loop over is an iterable. Let’s talk about looping.
Strings, lists, and tuples are all iterables. We’ll see more iterables later.
Loop Exercises
Hint
If you get stuck for a minute or more, try searching Google or using help.
If you’re stuck for more than a few minutes, some of these links might be helpful for some of the exercises below:
Starting with a vowel
File: Edit the get_vowel_names function in the loops.py file that is in the exercises directory.
Test: Run python test.py get_vowel_names in your exercises directory.
Exercise: Make a function that accepts a list of names and returns a new list containing all names that start with a vowel. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:
>>> from loops import get_vowel_names
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> get_vowel_names(names)
['Alice']
>>> names = ["Scott", "Arthur", "Jan", "elizabeth"]
>>> get_vowel_names(names)
['Arthur', 'elizabeth']
Note
Want to test this out manually (instead of using python test.py)?
You could could create a file called get_vowel_names_test.py with your own test code:
from loops import get_vowel_names
print('Calling get_vowel_names(["Alice", "Bob", "Christy", "Jules"])')
print("Expected: ['Alice']")
print(" Actual:", get_vowel_names(["Alice", "Bob", "Christy", "Jules"]))
print()
print('Calling get_vowel_names(["Scott", "Arthur", "Jan", "elizabeth"])')
print("Expected: ['Arthur', 'elizabeth']")
print(" Actual:", get_vowel_names(["Scott", "Arthur", "Jan", "elizabeth"]))
Then you can run that file to test your code:
$ python get_vowel_names_test.py
Average
File: Create a file average.py in the modules sub-directory of the exercises directory.
Test: Run python test.py average.py from your exercises directory.
Exercise: Make a program average.py that calculates the average of all given command-line arguments. To run it without using the test framework, see the example below. Be sure to move back to the exercises directory to run the test program.
To test it locally:
$ cd modules
$ python average.py 2 3 4 5 6 7
Average is 4.5
$ python average.py 2 3 4
Average is 3.0
Hint
You can get all command line arguments except the program filename with this trick:
import sys
arguments = sys.argv[1:]
We’ll learn about that [1:] syntax later.
Sum Timestamps
This is the sum_timestamps exercise in loops.py.
File: Edit the sum_timestamps function in the loops.py file that is in the exercises directory.
Test: Run python test.py sum_timestamps in your exercises directory.
Exercise: The sum_timestamps function takes a list of timestamp strings of “minute:seconds”, and returns a “minute:seconds” timestamp string that represents the total time from the list of timestamps.
Feel free to use the exercises parse_time and format_time from the “Function Exercises” section.
>>> from loops import sum_timestamps
>>> times = ["1:10", "0:12", "4:03", "2:45"]
>>> sum_timestamps(times)
'8:10'
>>> times = ["0:55", "0:55", "0:55", "0:55", "0:55"]
>>> sum_timestamps(times)
'4:35'
>>> sum_timestamps(["0:00"])
'0:00'
Here are the parse_time and format_time functions in case you need them:
def parse_time(time_string):
"""Return total seconds from string of minutes:seconds."""
sections = time_string.split(':')
return int(sections[0]) * 60 + int(sections[1])
def format_time(seconds):
"""Return a minutes:seconds string based on input seconds."""
sections = divmod(seconds, 60)
return f"{sections[0]}:{sections[1]:02d}"
Product
This is the product exercise in loops.py. Edit the loops.py file in the exercises directory to implement this exercise. To test it, run python test.py product in your exercises directory.
Write a product function that takes a list of numbers, multiplies the numbers together, and returns the result. Example:
>>> from loops import product
>>> product([5, 6, 8])
240
>>> product([10])
10
Note
Want to test this out manually (instead of using python test.py)?
You could could create a file called product_test.py with your own test code:
from loops import product
print("Calling product([5, 6, 8]")
print("Expected: 240")
print(" Actual:", repr(product([5, 6, 8])))
Then you can run that file to test your code:
$ python product_test.py
Sum All
File: Edit the sum_all function in the loops.py file that is in the exercises directory.
Test: Run python test.py sum_all in your exercises directory.
Exercise: Make a function that accepts a list of lists of numbers and returns the sum of all of the numbers.
>>> from loops import sum_all
>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> sum_all(matrix)
21
>>> sum_all([[0, 1], [4, 2], [3, 1]])
11
Flatten a Matrix
This is the flatten exercise in loops.py.
File: Edit the flatten function in the loops.py file that is in the exercises directory.
Test: Run python test.py flatten in your exercises directory.
Exercise: Make a function that will take a matrix (a list of lists) and return a flattened version of the matrix.
>>> from loops import flatten
>>> matrix = [[row * 3 + incr for incr in range(1, 4)] for row in range(4)]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> flatten(matrix)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Matrix From String
File: Edit the matrix_from_string function in the loops.py file that is in the exercises directory.
Test: Run python test.py matrix_from_string in your exercises directory.
Exercise: Modify the matrix_from_string function so that it accepts a string and returns a list of lists of integers (found in the string).
Example:
>>> from loops import matrix_from_string
>>> matrix_from_string("1 2\n10 20")
[[1, 2], [10, 20]]
X marks the spot
File: Edit the words_containing function in the loops.py file that is in the exercises directory.
Test: Run python test.py words_containing in your exercises directory.
Exercise: Modify the words_containing function so that it accepts a list of words and a letter and returns a list of all words in the string that contain the given letter. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:
>>> from loops import words_containing
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'y')
['My', 'my']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'i')
['life', 'is']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'm')
['My', 'my', 'message']
Consecutive Number Check
File: Edit the are_consecutive function in the loops.py file that is in the exercises directory.
Test: Run python test.py are_consecutive in your exercises directory.
Exercise: Modify the are_consecutive function so that it accepts a list of numbers and returns True if the numbers are consecutive, else return False. We aren’t going to worry about edge cases like an empty list or a list with only one number in it. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:
>>> from loops import are_consecutive
>>> are_consecutive([3, 4, 5, 6])
True
>>> are_consecutive([3, 5, 9])
False