11.count


#1

What did I do wrong? The print results in 0.


def count(sequence, item):
    number = 0
    for i in sequence:
        if i == item:
            number += 1
        return number
print count([3,2,1],1)


#2

a function ends the moment a return keyword is reached, this currently happens in the first iteration of the loop, change the indent of return so the whole loop can run


#3

I had the same issue as you.
I don't know if this is the most efficient code to solve the problem


def count(sequence, item):
found = 0

for thing in sequence:
    if thing == item:
        found += 1
    else:
        found += 0
return found

If the thing in the sequence didn't match the item, I told it to add 0 to found.
And then return found after the loop was done.


#4

why you use else? it doesn't do anything, you can just leave it out


#5

Because I'm still a beginner and like to see the code more explicitly.
But I've figured that I can leave it out...still lots to get better at


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.