HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

My attempt at FizzBuzz (Python 3)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonattemptfizzbuzz

Problem

Is this a good solution for FizzBuzz? What can I do better?

for num in range(1, 101):
    if num % 3 == 0:
        if num % 5 == 0:
            print("FizzBuzz")
        else:
            print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)

Solution

It's a good attempt, it reads easily and I like that you nested the FizzBuzz check within Fizz branch.

This doesn't look like most of the code you see in the wild, though, so a good exercise would be to extract a function for the FizzBuzz logic that is independent from the loop over numbers.

def get_fizzbuzz(num:int) -> str:
    result = ""
    # fizzbuzz logic
    if num % 3 == 0:
        if num % 5 == 0:
            result = "FizzBuzz"
        # ...
    return result


You could even make it more flexible by optionally allowing different numbers to be entered instead of 3 and 5, while still using 3 and 5 as default values, like so:

def get_fizzbuzz(num:int, fizz:int = 3, buzz:int = 5) -> str:
    result = ""
    # fizzbuzz logic
    if num % fizz == 0:
        if num % buzz == 0:
            result = "FizzBuzz"
        # ...
    return result


Then you can just call the function in a loop using the default values:

for num in range(1, 101):
    print(get_fizzbuzz(num))


Or alternatively with different values for fizz and buzz:

for num in range(1, 101):
    print(get_fizzbuzz(num, 5, 7))


That will help you make your code more modular.

Note that I used Python 3's type hints in the function definition, which are completely optional but can make the code more clear, as well as provide static code analysis with certain tools.

Code Snippets

def get_fizzbuzz(num:int) -> str:
    result = ""
    # fizzbuzz logic
    if num % 3 == 0:
        if num % 5 == 0:
            result = "FizzBuzz"
        # ...
    return result
def get_fizzbuzz(num:int, fizz:int = 3, buzz:int = 5) -> str:
    result = ""
    # fizzbuzz logic
    if num % fizz == 0:
        if num % buzz == 0:
            result = "FizzBuzz"
        # ...
    return result
for num in range(1, 101):
    print(get_fizzbuzz(num))
for num in range(1, 101):
    print(get_fizzbuzz(num, 5, 7))

Context

StackExchange Code Review Q#149256, answer score: 4

Revisions (0)

No revisions yet.