I\'m working on a Python exercise at Codecademy and got stuck on what looks like a simple problem:
Write a function
fizz_count()
that loops t
If x
is a sequence of elements, when you do
for i in x:
you are looping through the elements of x
, not through indexes.
So when you do
x[i]
you are doing
x[element]
which makes no sense.
What can you do?
You can compare the element with 'fizz'
:
for element in x:
if element == 'fizz':
# ...
When you used { for i in x } then here 'i' is the item of the list and not an index. Hence,
Corrected Code is:
def fizz_count(x):
count = 0
for i in x:
if i == 'fizz':
count = count + 1
return count
print fizz_count(['fizz', 'buzz'])
OUTPUT
1
You are passing in a list ['fizz', 'buzz'])
so i
is equal to fizz
or buzz
not an integer.
Try if i =="fizz"
def fizz_count(x):
count = 0
for i in x:
if i == 'fizz': # i will be each element in your list
count = count + 1
return count