Python For Loop Error
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 through all the elements of a list. When
Solution 1:
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:ifelement=='fizz':# ...
Solution 2:
You are passing in a list ['fizz', 'buzz'])
so i
is equal to fizz
or buzz
not an integer.
Try if i =="fizz"
deffizz_count(x):
count = 0for i in x:
if i == 'fizz': # i will be each element in your list
count = count + 1return count
Solution 3:
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 = 0for i in x:
ifi== 'fizz':
count = count + 1return count
print fizz_count(['fizz', 'buzz'])
OUTPUT
1
Post a Comment for "Python For Loop Error"