Can the first_three_multiples function be written so that it doesn't have three print statements?


#1

Question

In this exercise, the first_three_multiples() function has three print statements. Can this be done in some other way?

Answer

Yes, there are several ways in which you could condense the code. A straightforward way would be the use of a for loop as shown below. Rember that the range() function does not include the end number so the range produced by this code would be 1 … 3.

def first_three_multiples(num):
    for x in range(1, 4):
        print(num * x)
    return num*3

Expanding on this idea, you could also generalize the function to accept the multiple as a parameter so it would work for values other than 3.

def multiples(num, multiple):
    for x in range(1, multiple + 1):
        print(num * x)
    return num * multiple