Python Fizzbuzz问题与循环 [英] Python Fizzbuzz problems with loop
问题描述
我已经搜索了大约一个小时的答案,而且似乎大多数人使用与我不同的方式来编码fizzbuzz.
I've searched for the answer for about an hour, and it seems most people have coded fizzbuzz a different way than myself.
但是,在尝试了所有方法以找出为什么此简单代码无法正常工作后,我感到非常沮丧.
However, having tried everything to figure out why this simple code will not work I'm getting extremely frustrated.
谁能指出我确定的简单问题?该代码运行,但只返回值1.
Can anyone point out the simple problem I'm sure I'm having? The code runs but it just returns the value 1.
def fizzbuzz(intList):
for n in intList:
if n % 3 == 0 and n % 5 == 0:
return n.replace(str(n),"Fizzbuzz")
elif n % 3 == 0:
return n.replace(str(n),"Fizz")
elif n % 5 == 0:
return n.replace(str(n),"Buzz")
else:
return n
推荐答案
代码正在返回1
,因为考虑此列表[1,2,3,4,5,6,7,8,9,10]
.这三个条件都将得到false
,最后一个else
将返回1
.如果需要答案,请将其附加到列表中.
The code is returning 1
because consider this list [1,2,3,4,5,6,7,8,9,10]
. All three conditions will get false
and the last else
will return 1
. If you want the answer, append them into list.
类似这样的东西:
def fizzbuzz(intList):
temp = []
for n in intList:
if n % 3 == 0 and n % 5 == 0:
temp.append("Fizzbuzz")
elif n % 3 == 0:
temp.append("Fizz")
elif n % 5 == 0:
temp.append("Buzz")
else:
temp.append(n)
return temp
print fizzbuzz(range(1,20))
这篇关于Python Fizzbuzz问题与循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!