There are a handful of problems here:
- You're trying to iterate over
fizz_count
. But fizz_count
is your function. x
is your passed-in argument. So it should be for x in x:
(but see #3).
- You're accepting one argument with
*x
. The *
causes x
to be a tuple of all arguments. If you only pass one, a list, then the list is x[0]
and items of the list are x[0][0]
, x[0][1]
and so on. Easier to just accept x
.
- You're using your argument,
x
, as the placeholder for items in your list when you iterate over it, which means after the loop, x
no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x
afterward, but for clarity it's better to use a different variable name.
- Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list
has a count()
method, as does tuple
, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!