What is Iteration?

Iteration is basically repetition. In code, it is always helpful to have a system in place to repeat a function a certain amount of times, because copy-pasting functions over and over is both unnecessary complicated and unprofessional.

Pretty much every single code language uses loops of some kind, but in this lesson, we use Python because it has a very learning-friendly syntax.

Conditional Iteration

Most of the time, a function iterates a certain number of times based on the purpose it's supposed to serve. For example, if your function is supposed to multiply a number by 8 four times, you could do something like this, but you definitely shouldn't.

number = 2
def multiplyby8(num):
    global newnum
    newnum = num * 8
    print(newnum)

print('Multiplying', number, 'by 8 four times:')
multiplyby8(number)
multiplyby8(newnum)
multiplyby8(newnum)
multiplyby8(newnum)
Multiplying 2 by 8 four times:
16
128
1024
8192

Instead, automate the process using loops. In this case, we used a "while" loop. There will be more about loops later in the second part of this lesson. The function loops until the condition of the function having been repeated 4 times is satisfied.

number = 2
def multiplyby8_4times(num):
    print('Multiplying', num, 'by 8 four times:')
    i = 0 #i starts at 0
    while i < 4: #the function will repeat until i >= 4
        num = num * 8
        print(num)
        i += 1 #i increments each time

multiplyby8_4times(number)
Multiplying 2 by 8 four times:
16
128
1024
8192

(It would actually be more efficient to just multiply the number by 4096 or 84, but this is just for demonstration.)

Iteration Based on Lists and Dictionaries

Most code languages have some form of "for" loop. This type of loop checks the information stored within a list and uses it as specified by the given variable (in this case, 'number').

numlist = [1, 2, 3, 4] #more numbers = increase the amount of times it iterates
#since numlist is a list of single numbers, it understands 'number' as each number
for number in numlist:
    prod = number * 2
    print(str(number), "times 2 is equal to", str(prod) + ".")
1 times 2 is equal to 2.
2 times 2 is equal to 4.
3 times 2 is equal to 6.
4 times 2 is equal to 8.

Lists with multiple items at each index can be formatted like this.

petlist = [("Dogs", 1), ("Cats", 2), ("Fish", 0)]

print("Your pets:")
for pet, number in petlist: #in order, the first and then the second
    print(pet + ": ", number)
Your pets:
Dogs:  1
Cats:  2
Fish:  0

In cases like this, however, it is usually preferable to use a dictionary. This makes the information clearer.

Using multiple loops, we can even dig deeper into collections of information during a "for" loop like in the example below.

drewpets = [("Drew", ({"dogs": 1, "cats": 1, "fish": 0}))]
ajpets = [("AJ", {"dogs": 1, "cats": 0, "fish": 329})]
johnnypets = [("Johnny", {"dogs": 2, "cats": 0, "fish": 0})]
allpets = [drewpets, ajpets, johnnypets] #a collection of all pet lists

for person in allpets:
    for name, dict in person: #unpacking the name and dictionary
        print(name + "'s pets:")
        for pet, num in dict.items(): #use .items() to go through keys and values
            print(pet.capitalize() + ":", num) #capitalizes first letter
    print("")

Try running this on your own and see if you can understand it.

Hack opportunity: make your own function that uses multiple "for" loops within each other to unpack and display elements in a list.