Loop the Loop
Last time We learned about the for
loop. This loop uses an iterable as "food." Iterables
contain a iterators, which just walk from item to item in an iterable.
What is an iterable? For now,
think this way. Iterables are "food" for for
loops. Iterables contain an object called an
iterator, which causes the elements to be visited
in succession to a for
loop to act upon. Here is a field
guide to iterators for our favorite types. One nice thing
about iterators: they do not change the collection they are walking
through.
- strings This iterator walks through a string one character at a time in index order.
- lists and tuples Their iterators walk through one element at a time in index order.
- sets The iterator walks through the set in no particular order.
- dictionaries The iterator walks the keys of a dictionary one key at a time in no particular order.
- file objects The iterator walks through a file one line at a time.
Here are some other iterables.
- range objects These specify arithmetic sequences of integers
- dictionary_keys object This is what you get when you
use the
keys()
on a dictionary. - dictionary_values object This is what you get when
you use the
values()
method on a dictionary.
for
loop structure The for
loop looks like this.
x = [1,2,3,4] for k in x: #k is the "hummingbird" that visits each item in x. print(k) #this can be several lines of code that do stuff with k.
Let's try some mini-challenges.
1. Make this appear.
0 -1 ----4 ---------9 ----------------16 -------------------------25 ------------------------------------36 -------------------------------------------------49 ----------------------------------------------------------------64
2. Write a program named skippy.py
that accepts a filename as an argument and which
prints out every other line in the file. Hint: One way to
go is to use the readlines
method on a file object. Another
way: Use conditional logic to print only the desired ines.
3. Here is a way to see if a integer n >= 2
is prime.
Check and see if n%2 == 0. If it is, return False. Now try n%3 == 0 and do
the same. Keep going until you get to n%(n-1) == 0. If all of the
cases fail, return True
Prime: 97, not prime: 64.
4. The \(n\)th triangle number, \(T_n\) is defined by
$$T_n = \sum_{k=1}^n k = 1 + 2 + 3 + \cdots + n.$$for \(n \ge 1\). Write a function that computes this. Here is a test: \(T_{100} = 5050\).