每次触发if循环时如何更改if循环中变量的值?

时间:2013-07-16 01:24:27

标签: python loops

我正在尝试使用codeacademy来学习python。赋值是“编写一个名为fizz_count的函数,它将列表x作为输入,并返回该列表中字符串”fizz“的计数。”

# Write your function below!
 def fizz_count(input):
     x = [input]
     count = 0
     if x =="fizz":
         count = count + 1
         return count

我认为if循环上面的代码很好,因为错误消息(“你的函数在fizz_count上失败([u'fizz',0,0]);当它应该返回1时它返回None。”)只出现当我添加该代码。

我还尝试创建一个新变量(new_count)并将其设置为count + 1但是这给了我相同的错误消息

我非常感谢你的帮助

5 个答案:

答案 0 :(得分:3)

问题是你没有循环。

# Write your function below!
 def fizz_count(input):
     count = 0
     for x in input: # you need to iterate through the input list
         if x =="fizz":
             count = count + 1
     return count

使用.count()函数有一种更简洁的方法:

def fizz_count(input):
    return input.count("fizz")

答案 1 :(得分:1)

摆脱x = [input],只创建另一个包含列表input的列表。

  

我认为if循环上面的代码很好

if不循环;你可能正在寻找for

for x in input:  # 'x' will get assigned to each element of 'input'
    ...

在此循环中,您将检查x是否等于"fizz"并相应地增加计数(正如您当前使用if语句一样)。

最后,将您的return语句移出循环/ if语句。您希望在循环之后执行该操作,因为您总是希望在返回之前遍历列表

作为旁注,您不应使用名称input,因为该名称已分配给built-in function

全部放在一起:

def fizz_count(l):

    count = 0  # set our initial count to 0

    for x in l:  # for each element x of the list l
        if x == "fizz":  # check if x equals "fizz"
            count = count + 1  # if so, increment count

    return count  # return how many "fizz"s we counted

答案 2 :(得分:0)

def fizz_count(x):                       #DEFine func
    count = 0                            #set counter to zero
    for item in x:                       
        if item == "fizz" :               
            count += 1                   #iterate counter +1 for each match
    print count                          #print result
    return count                         #return value 
fizz_count(["fizz","buzz","fizz"])       #call func 

答案 3 :(得分:0)

试试这个:

# Write your function below!
def fizz_count(x):
    count = 0
    for item in x:
        if item == "fizz": 
            count = count + 1
    return count

答案 4 :(得分:-2)

def fizz_count(input)
    count = 0
    for x in input:
        count +=  1 if x=="fizz" else 0
    return count