Python, Fizz Buzz inserting the range as a parameter of the function

1.8k Views Asked by At

I am using the fizz buzz exercise to learn a little about python. I have hardcoded a range of 1-100 but I was curious how I might accomplish the same result by passing the range into the function using the parameter?

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

There are 2 best solutions below

1
On BEST ANSWER
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))
0
On

You could use Python's itertools.count and pass in just the max value.

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)