patternpythonMajor
1, 2, Fizz, 4, Buzz: FizzBuzz
Viewed 0 times
buzzfizzfizzbuzz
Problem
I just recently started working on python (interesting language, actually), and, as I always do when I learn a new language (with the exception of BrainFuck, that's too hard), I write a FizzBuzz program.
I notice there is no error-checking, so my program would have problems with incorrect input, but please ignore that as I haven't gotten to that part yet.
Code:
The code will take a
Concerns:
I notice there is no error-checking, so my program would have problems with incorrect input, but please ignore that as I haven't gotten to that part yet.
Code:
def getString(num, fizz, buzz):
if num % (fizz * buzz) == 0:
return "FizzBuzz"
elif num % fizz == 0:
return "Fizz"
elif num % buzz == 0:
return "Buzz"
else:
return num
def fizzbuzz(maxNum, fizz, buzz):
num = 1;
while num <= maxNum:
print(getString(num, fizz, buzz))
num += 1
fizz = int(input("Enter the number to Fizz: "))
buzz = int(input("Enter the number to Buzz: "))
maxNum = int(input("Enter the maximum number: "))
fizzbuzz(maxNum, fizz, buzz)The code will take a
fizz, buzz, and a maxNum as input, and will output, all the fizzing and buzzing the code is doing.Concerns:
- Does it follow Python conventions?
Solution
getStringandmaxNumshould beget_stringandmax_num, by PEP 8 recommendation.
getStringsometimes returns a number, and sometimes returns a string. This violates the expectation set up by the function name. Also, a function that is indecisive about its return type is harder to work with.
num = 1;← No semicolons in Python, please.
- The
fizzbuzzloop is written idiomatically asfor num in range(1, maxNum + 1): …
Context
StackExchange Code Review Q#113990, answer score: 24
Revisions (0)
No revisions yet.