Previous Lesson Current Lesson Next Lesson

Question 1

n = 1

while n <= 5:
    print(n)
    print(n + 1)

This will output:

1
2
2
3
3
4
4
5
5
6

We iterating over the numbers from 1 to 5, so the initial value is 1, which we assign to our variable n. So long as the condition n <= 5 holds, we continue printing out n and n + 1 as desired.

Question 2

def f(n):
    l = []

    # We assume `n` is odd.
    while n >= 1:
        l.append(n)

        # Alternatively, `n = n - 2`.
        n -= 2

    return l

Because n is assumed to always be an odd integer, we will always append n first. n - 2 is odd so long as n is odd, so we keep appending n until decrementing n by 2 produces a number less than 1.

For example, if we pass in n = 5, we get:

[5, 3, 1]

Question 3

If we multiply a * b, we are adding a to itself b times. This suggests the following implementation below using while loops:

def multiply(a, b):
    product = 0
    
    while b > 0:
        product += a
        b -= 1

    return product

If b = 0, the while loop condition is already false, so product = 0 as desired. Otherwise, we continue adding a to our product until b reaches 0, by which we would have added a a sufficient number of times to get our desired product: a * b.