Uncomment for mathJax 2 March 2021

2 March 2021

Loop the Loop

picture of an airplane looping

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.

Here are some other iterables.

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\).