Loops¶
For Loop¶
Something is an iterable if you can iterate over it using a “for loop”. Strings, lists, and tuples are all iterables.
Let’s make 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
Loop Exercises¶
Starting with a vowel¶
Make a function that accepts a list of names and returns a new list containing all names that start with a vowel. It should work like this:
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> vowel_names(names)
['Alice']
>>> names = ["Scott", "Arthur", "Jan", "Elizabeth"]
>>> vowel_names(names)
['Arthur', 'Elizabeth']
Average¶
Make a program average.py that calculates the average of all given command-line arguments and prints a message “No numbers to average!” if there are no arguments given:
$ python average.py
No numbers to average!
$ python average.py 2 3 4 5 6 7
Average is 4.5
$ python average.py 2 3 4
Average is 3.0
Bonus: X marks the spot¶
- Create a string containing the declaration of independence
- Print all words in the declaration of independence that contain the letter “x”
Bonus: Secret Message¶
- Create a string containing the
declaration of independence - Get a list of all uppercase letters in the declaration of independence
- Find a secret 4 letter word in this uppercase letter list. The word starts at index 374 ends at index 382, and skips every other letter
Enumerate¶
In C, Java, and other languages our for loops require us to increment an index counter to loop over lists or arrays. Python doesn’t do this.
But what if while looping over our list we actually want the index of each item?
We can use the enumerate function for this:
>>> numbers = [3, 4, 8]
>>> for item in enumerate(numbers):
... print(item)
...
(0, 3)
(1, 4)
(2, 8)
This function makes a new object that we can iterate over to get tuples containing the index of each item and the value of the item.
While enumerate gives us an index, similar to for loops in other programming languages, it does not require us to increment this index. This happens automatically for each iteration of the loop.
Note that the returned object is not a list, but we can make it a list using the list constructor:
>>> enumerate(numbers)
<enumerate object at 0x7f02ff21af30>
>>> list(enumerate(numbers))
[(0, 3), (1, 4), (2, 8)]
Let’s write code that will print the index of each item:
>>> for item in enumerate(numbers):
... print("Item {} is {}".format(item[0], item[1]))
...
Item 0 is 3
Item 1 is 4
Item 2 is 8
That’s a little awkward.
We learned about tuple unpacking and multiple assignment earlier. So we know we can do this:
>>> items = list(enumerate(numbers))
>>> items
[(0, 3), (1, 4), (2, 8)]
>>> items[0]
(0, 3)
>>> i, value = items[0]
>>> i
0
>>> value
3
We can actually use this in for loops also. Let’s use tuple unpacking to make that for loop more clear:
>>> for i, num in enumerate(numbers):
... print("Item {} is {}".format(i, num))
...
Item 0 is 3
Item 1 is 4
Item 2 is 8
Range¶
Python’s range function allows us to get integer numbers between two numbers:
>>> for n in range(0, 5):
... print(n)
...
0
1
2
3
4
Note that the numbers go up to but not including the final value.
If the first argument is 0, we can leave it off:
>>> for n in range(5):
... print(n)
...
0
1
2
3
4
We can specify a third argument as a step:
>>> for n in range(0, 100, 10):
... print(n)
...
0
10
20
30
40
50
60
70
80
90
Range Exercises¶
Power By Index¶
Make a function, ith_item_power, that accepts a list of numbers and an index number and returns the i-th element raised to the i-th power where i is the given index number. For example:
>>> ith_item_power([3, 2, 5], 2)
25
>>> ith_item_power([5, 6, 2, 7, 3], 4)
81
Power List By Index¶
Make a function, power_list, that accepts a list and returns a new list that contains each number raised to the i-th power where i is the index of that number in the given list. For example:
>>> power_list([3, 2, 5])
[1, 2, 25]
>>> numbers = [78, 700, 82, 16, 2, 3, 9.5]
>>> power_list(numbers)
[1, 700, 6724, 4096, 16, 243, 735091.890625]
Divisible¶
Make a list of all numbers between 100 and 300 that are divisible by both 6 and 10.
99 Bottles¶
Write a program called bottles.py that when executed will print the lyrics to the song “99 bottles of beer”. Feel free to substitute your favorite beverage in place of beer.
The song has 100 verses. Each verse is structured like this:
99 bottles of milk on the wall, 99 bottles of milk.
Take one down, pass it around, 98 bottles of milk on the wall...
This same verse is repeated, each time with one less bottle. So the second verse is:
98 bottles of milk on the wall, 98 bottles of milk.
Take one down, pass it around, 97 bottles of milk on the wall...
The last verse does not use numbers. The last two verses are:
1 bottle of milk on the wall, 1 bottle of milk.
Take one down, pass it around, no more bottles of milk on the wall...
No more bottles of milk on the wall, no more bottles of milk.
Go to the store and buy some more, 99 bottles of milk on the wall...