Block F

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

ZhangB


for i in range(9):
    print("-" * i ** 2 + str(i ** 2))

parkerC


arr = [0,1,4,9,16,25,36,49,64]
for i in arr:
    print("-"*i, end='')
        print(i)

fujitaT


for k in range (9):
    y=k**2
    x = y*"-"
    print(f"{x}{y}")

gamboaP


for x in range(9):
    print("-"*x*x+f"{x*x}")

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.

gamboaP


from sys import argv
file_name = argv[1]
num = 0
with open(file_name, "r") as fp:
    for k in fp:
        num = (num+1)%2
        if num == 1:
            print(k, end="")

burgessK


from sys import argv
file_name = argv[1]

fp = open(file_name, 'r')
fplist = fp.readlines()
for k in range(0,len(fplist)//2):
    print(fplist[k*2], end='')

haughanZ


from sys import argv
for line in open(argv[1], "r").readlines()[::2]:
    print(line, end="")

morrison closes file too


from sys import argv
with open(argv[1], "r") as fp:
    for line in fp.readlines()[::2]:
        print(line, end="")

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.

hauganZ


def isPrime(n):
    return all(n%i for i in range(2,n))

def is_prime(num, start=2):
    if num == 1:
        return True
    if num%start==0:
        return False
    if start == num-1:
        return True
    return is_prime(num, start+1)
print(is_prime(97))
print(is_prime(64))

morrison simple solution


def is_prime(num):
    if num == 2:
        return True
    for k in range(2, num)
        if n%k == 0:
            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\).

hauganZ


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

gamboaP


def triangle(end, num=1, total=0):
    if end < num:
        return "Invalid input"
    total += num
    if num == end:
        return total
    return triangle(end, num+1, total)

gamboaP again!


def triangle1(end):
    total = 0
    for num in range(end+1):
        total += num
    return total

n = 1
def triangle(n):
    for i in range(1,n):
        n = n+i
    print(n)