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

Fizzbuzz in Python

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

Problem

I'm new to Python and wondering what can be improved with the following super novice program - in terms of the solution and code style etc.

test_fizzbuzz.py

import unittest
import fizzbuzz

class TestFizzbuzzFunctions(unittest.TestCase):

    def test_it_converts_multiples_of_three_to_fizz(self):
        self.assertEqual(fizzbuzz.process_number(6), 'fizz')

    def test_it_converts_multiples_of_five_to_buzz(self):
        self.assertEqual(fizzbuzz.process_number(10), 'buzz')

    def test_it_converts_multiples_of_three_and_five_to_fizzbuzz(self):
        self.assertEqual(fizzbuzz.process_number(15), 'fizzbuzz')

    def test_it_does_not_convert_numbers_that_are_not_multiples_of_three_or_five(self):
        self.assertEqual(fizzbuzz.process_number(11), 11)

if __name__ == '__main__':
    unittest.main()


fizzbuzz.py

def process_number(number):
    result = ''
    if number % 3 == 0:
        result += 'fizz'
    if number % 5 == 0:
        result += 'buzz'

    return result or number

Solution

This does not appear to be a true FizzBuzz program. A FizzBuzz program, according to the tag wiki, iterates through the numbers 1-100 and prints the values according to the rules you have.

One thing you did correctly is this:

if __name__ == '__main__':


Many beginners fail to do this. Also, you used snake_case, which is Python standard too.

One thing I found slightly difficult to understand is this:

return result or number


This would not compile in many languages, and it also allows the method to have two return types - a string and an int. I would adjust this to use an if statement and convert the number to a string:

if result != '':
    return result

return str(number)


This way, the method always returns a string.

Because this is just FizzBuzz, if you are going to create a second method for handling it at all, I would just print from within the function, then you do not need to worry about return type:

def process_number(number):
    result = ''
    if number % 3 == 0:
        result += 'fizz'
    if number % 5 == 0:
        result += 'buzz'

    if result != '':
        print(result)
    else:
        print(number)

Code Snippets

if __name__ == '__main__':
return result or number
if result != '':
    return result

return str(number)
def process_number(number):
    result = ''
    if number % 3 == 0:
        result += 'fizz'
    if number % 5 == 0:
        result += 'buzz'

    if result != '':
        print(result)
    else:
        print(number)

Context

StackExchange Code Review Q#81765, answer score: 2

Revisions (0)

No revisions yet.