Python,Fizz Buzz插入范围作为函数的参数

时间:2014-12-10 18:20:11

标签: python fizzbuzz

我正在使用fizz buzz练习来学习一些关于python的知识。我已经硬编码了1-100的范围,但我很好奇如何通过使用参数将范围传递给函数来实现相同的结果?

numbers = range (1,101)
def fizzbuzz(numbers):
    for each in numbers:
        if each % 3 == 0 and each % 5 == 0:
            print "fizzbuzz"
        elif each % 3 == 0:
            print "fizz"
        elif each % 5 == 0:
            print "buzz"
        else:
            print each
print fizzbuzz(numbers)

2 个答案:

答案 0 :(得分:1)

您可以使用Python的itertools.count并仅传入最大值。

https://docs.python.org/2/library/itertools.html

def fizzbuzz(num):
    for i in itertools.count(start=1,step=1):
        if (i==num):
            break
        ..fizzbuz logic

fizzbuzz(num)

答案 1 :(得分:-1)

def fizzbuzz(num_range):
    for each in num_range:
        if each % 3 == 0 and each % 5 == 0:
            print "fizzbuzz"
        elif each % 3 == 0:
            print "fizz"
        elif each % 5 == 0:
            print "buzz"
        else:
            print each

print fizzbuzz(range (1,101))