Using Loops#

Loops allow us to reduce the amount of time we have to write instructions. If we can run the instructions multiple times, then we simplify the code, and can make more progress.

While Loops#

def while1():
    x = 1
    while x <= 5:
        #add 1 to x (yes, you can use the same variable to assign)
        x = x + 1
        #calculate y
        y = x**2 - 1
        #print
        print(f"x={x} y={y}")
    #After the loop:    
    z = x * y
    print(f"z={z}")

def while2():
    count_loops = 0
    x = 0
    while x <= 5:
        x = x + 1
        y = x**2 - 1
        count_loops += 1
        print(f"x={x} y={y}")
    # Display counter outside loop​
    print(f"Counter = {count_loops}")

def while3(): #stuck in a loop
    count_loops = 0
    x = 1
    while x <= 5:
        x = x
        y = x**2 - 1
        count_loops += 1
        print(f"x={x} y={y}")
    # Display counter outside loop​
    print(f"Counter = {count_loops}")


while1()
#while2()
#while3()
x=2 y=3
x=3 y=8
x=4 y=15
x=5 y=24
x=6 y=35
z=210

For Loops#

def for1():
    for x in [7,9,16]:
        y = x+2
        print(f"x={x}, y={y}")

def for2():
    for x in range(1,10):
        y = x**2
        print(f"x={x}, y={y}")

def forList():
    a=range(20)
    List1 = []
    for x in a:
        List1.append(x+4)
        print(List1)
    print(List1)

def nestFor():
    a_V = []
    for ii in range(1,3):
        for jj in range(1,6,2):
            z = ii + jj
            a_V.append(z)
            print(f"ii:{ii}, jj:{jj}, a_V:{a_V}")

def leaveLoop():
    numbers = [1, 2, 3, 5, 7, 10, 15, 22, 25, 28]
    for num in numbers:
        if num > 20:
            print("Found a number greater than 20!")
            break
        elif num % 5 == 0:
            continue
        elif num == 2:
            pass
        else:
            print(num)


#for1()
#for2()
#forList()
nestFor()
#leaveLoop()
ii:1, jj:1, a_V:[2]
ii:1, jj:3, a_V:[2, 4]
ii:1, jj:5, a_V:[2, 4, 6]
ii:2, jj:1, a_V:[2, 4, 6, 3]
ii:2, jj:3, a_V:[2, 4, 6, 3, 5]
ii:2, jj:5, a_V:[2, 4, 6, 3, 5, 7]

Recursion (Ignore this if you want…)#

def collatz_iter(n):
    #Determine stopping time using iteration.
    steps = 0
    while n > 1:
        steps += 1
        if n%2:  # n is odd​
            n = 3*n + 1
        else:  # n is even​
            n = n // 2
    return steps

def collatz_recur(n, steps):
#    Determine stopping time using recursion.
    if n == 1:
        return steps
    elif n%2:  # n is odd​
        n = 3*n + 1
    else:  # n is even​
        n = n //  2
    return collatz_recur(n, steps+1)

def hanoiRecurs(n, source, auxiliary, destination):
    """
    Solves the Towers of Hanoi puzzle recursively.
        n: The number of disks to move.
        source: The starting peg.
        auxiliary: The intermediate peg.
        destination: The final peg.
    """
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    hanoiRecurs(n - 1, source, destination, auxiliary)
    print(f"Move disk {n} from {source} to {destination}")
    hanoiRecurs(n - 1, auxiliary, source, destination)


#collatz_iter(123)
#collatz_recur(123,0)
hanoiRecurs(4, 'A', 'B', 'C')
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
Move disk 4 from A to C
Move disk 1 from B to C
Move disk 2 from B to A
Move disk 1 from C to A
Move disk 3 from B to C
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C