Python for loop error

前端 未结 3 1187
盖世英雄少女心
盖世英雄少女心 2021-01-28 17:38

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

相关标签:
3条回答
  • 2021-01-28 18:11

    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':
            # ...
    
    0 讨论(0)
  • 2021-01-28 18:14

    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
    
    0 讨论(0)
  • 2021-01-28 18:21

    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
    
    0 讨论(0)
提交回复
热议问题