Last answered:

27 Jun 2023

Posted on:

23 Jun 2023

0

count functioning returning the result as 1.

def count(numbers):
    total = 0
    for x in numbers:
        if x < 20:
            total += 1
            return total
    
list_1 = [1,2,3,15,22]
count(list_1)
1

please explain why the result is showing as '1', while the actual count of numbers should be 4.

Thank you.

1 answers ( 0 marked as helpful)
Instructor
Posted on:

27 Jun 2023

0

Hi Thu!
Thanks for reaching out.


Please, use the following code:

def count(numbers):
    total = 0
    for x in numbers:
        if x < 20:
            total += 1
    return total
    
list_1 = [1,2,3,15,22]
count(list_1)

The return statement and the for loop should have the same indentation. This is because we want to return a result only after the for loop iterates through all elements.



Hope this helps.
Best,
Tsvetelin

Submit an answer