# Count

#1

Oops, try again. Your function fails on count([4, 'foo', 5, 'foo'],5). It returns 0 when it should return 1.

my if statement clearly states that when num = items that we should add 1 to number so that's what confuses me?

def count(sequence, item):
number = 0
for num in sequence:
if num == item:
number += 1
elif num != item:
return 0
print number

#2

Hi, @jens89 ,

You have this ...

elif num != item:
return 0

If an item is found that does not match num, is it appropriate to return a value of 0? Perhaps there are other items that do match num.

After all the counting is done, you should return the value of number rather than print it, as you have done here ...

print number

#3

you are absolutely right about returning the value of 0. what I thought about doing (although I'm sure it's not correct either) was that instead of

return 0

I changed it to

number += 0

also if an item is found that doesn't mach num then we shouldn't count them anyway right? I'm not sure which other items could match num and that we should count?

#4

You don't need the elif block at all. Whenever an item is found that does not match num, just leave number as it is. No action needs to be taken in those cases. A line such as the following is not needed ...

number += 0

Finally, when all counting is done ...

return number

#5

haha I got it

def count(sequence, item):
number = 0
for num in sequence:
if num == item:
number += 1
else:
num = num
return number

that makes much more sense.

thanks!

#6

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