Block B

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.

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

Targett


x = [0, 1, 2, 3, 4, 5, 6, 7, 8]
for i in x:
    square = i**2
    print("-" * square + str(square))

Crowley


for k in range (0, 9):
    print("-" * k**2 + str(k**2))

Surkin "unrolling" a loop.


d = "----------------------------------------------------------------"
print(0)
print(d[0] + "1")
print(d[0:3]+"4")
print(d[0:8]+"9")
print(d[0:15]+"16")
print(d[0:24]+"25")
print(d[0:35]+"36")
print(d[0:48]+"49")
print(d[0:63]+"64")

Bunch


for k in range(0,9):
    print("-"*k*k + str(k * k))

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.

Mitchell


from sys import argv
import os

if len(argv) < 2:
    print("please give a read file input")
    quit()

file_name = argv[1]

fp = open(file_name, 'r')

for i, l in enumerate(fp):
    line = l
    if (i%2 == 0):
        print(line)

Lei


from sys import argv

file_name = argv[1]
fp = open(file_name, "r")
lines = fp.readlines()
print(lines[::2])

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.

Moore


n = int(input("Enter a number you wish to check if prime.    "))
c = False
if n >= 2:
    for k in range(2,n):
        if n%k == 0:
            c = True
            break
if c == False:
    print("Your number is prime")
else:
    print("Your number is composite")

Targett


def prime(n):
    if n >= 2:
        for k in range(2, n-1):
            if not ( n % k ):
                return False
    return True
print(prime(97))
print(not prime(64))

Crowley


def prime(n):
    if n >= 2:
        for k in range(2, n-1):
            if not ( n % k ):
                return False
    return True

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

Moore


def tri(n):
    sum = 0
    for k in range(1, n+1):
        sum += k
    return sum
print(tri(int(input("Which triangle number do you wish to find?    "))))

Mitchell


def triNum(n):
    # either n or n+1 must be even, therefore integer result
    return n*(n+1)//2

Lasowski


def triangle(n): 
    return n * (n + 1) / 2

Lasowksi, again


def triangle(n): 
    sum(range(n+1))