Reputation: 43
I am trying to figure out this problem on Codecademy, but I can not figure it out. Ok so I need to make this so it will return the number of times a word is said in a list.
Here is what it says to do:
Write a function that counts how many times the string "fizz" appears in a list.
1.Write a function called fizz_count that takes a list x as input.
2.Create a variable count to hold the ongoing count. Initialize it to zero.
3.for each item in x:, if that item is equal to the string "fizz" then increment the count variable.
4.After the loop, please return the count variable.
For example, fizz_count(["fizz","cat","fizz"]) should return 2.
Then here is what I have written:
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
To look at this lesson the number is A Day at the Supermarket 4/13
Upvotes: 1
Views: 4166
Reputation: 3661
I'm aware that the assignment requires you to write an explicit for loop for counting, but this kind of error due to misindentation is exactly why I personally prefer using functional idioms in python. You can implement this like:
def fizz_count(x):
return len([item for item in x if item == "fizz"])
Upvotes: 1
Reputation: 501
return is part of the if block. Do not return until the for block has finished:
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
Upvotes: 1
Reputation: 34146
What happens is that when a return
statement is reached, the function will be exited. What you should do instead is to return the count after the for
loop ends:
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
Note:
Upvotes: 3
Reputation: 18467
You're so close! You've just got the indentation wrong.
for item in x:
if item == 'fizz':
count = count + 1
return count # Returns any time we hit "fizz"!
for item in x:
if item == 'fizz':
count += 1 # how we normally write this
return count # after the loop, at the base indent level of the function
Upvotes: 8
Reputation: 4005
You're almost there. The indentation is wrong. Your code should be:
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
Upvotes: 4
Reputation: 60
put your return at the end of your for loop. so it would be:
for item in x:
if item == "fizz":
count+= 1
return count
Upvotes: 2
Reputation: 2733
You need to place the return statement after the for loop
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
Upvotes: 2
Reputation: 10742
def fizz_count(words_list):
return len([word for word in words_list if word == 'fizz'])
OR
def fizz_count(words_list):
return words_list.count('fizz')
Upvotes: 2
Reputation: 2481
You're returning count
inside your for
loop; you should finish iterating over your list, and then return.
Upvotes: 4