noxxic
noxxic

Reputation: 3

Write function mult3() that takes as input a list of integers and prints only the multiples of 3, one per line

I need to write a function which does the following: 1. Takes a list as input. 2. Print only multiples of 3, one per line.

I figured it out task 1, but I am stuck on 2 on the one per line part.

def mult3(lst):
    for num in lst:
        if num % 3 == 0:
            print(num, end=' ')
        print()

I know the problem is in the last print() function, in the current code it still prints a new line but just leaves it empty. I think this happens because of the fact that:

    for num in lst:
        if num % 3 == 0:  
        print()

Will print a line even if the number is not a multiple of 3. This makes sense but I cant figured out how to only print a line when if num % 3 == 0: is true

Upvotes: 0

Views: 454

Answers (1)

Hamza
Hamza

Reputation: 6045

simply print new line character within the if statement as endline string:

def mult3(lst):
    for num in lst:
        if num % 3 == 0:
            print(num, end='\n')

Upvotes: 1

Related Questions