"""This is the solution in its most basic form, allowing the upper number to be defined by user input"""
def fizzBuzz():
x = int(input("Enter a number up to which you would like to 'FizzBuzz': "))
nums = range(1,x+1)
for n in nums:
if n % 3 == 0 and n % 5 == 0:
print "FizzBuzz",
elif n % 3 == 0:
print "Fizz",
elif n % 5 == 0:
print "Buzz",
else:
print n,
fizzBuzz()
"""Here I have added the absolute function to return a opsitive integer of whatever is input"""
def fizzBuzz():
x = abs(int(input("Enter a number up to which you would like to 'FizzBuzz': ")))
nums = range(1,x+1)
for n in nums:
if n % 3 == 0 and n % 5 == 0:
print "FizzBuzz",
elif n % 3 == 0:
print "Fizz",
elif n % 5 == 0:
print "Buzz",
else:
print n,
fizzBuzz()
Still going strong, but...
What if someone enters a number as a string (or any other string?)
"""With this change, the while statement will insist that a valid input is provided
before the code will continue, and any name errors are handled with a bespoke message"""
def fizzBuzz():
while True:
try:
x = abs(int(raw_input("Enter a number up to which you would like to 'FizzBuzz': ")))
break
except ValueError:
print("Error! You must enter a number, for example: 6, 93, 529 etc.")
nums = range(1,x+1)
for n in nums:
if n % 3 == 0 and n % 5 == 0:
print "FizzBuzz",
elif n % 3 == 0:
print "Fizz",
elif n % 5 == 0:
print "Buzz",
else:
print n,
fizzBuzz()
Okay, everything works as planned!
Ignoring the user input for readability, I will now look at other ways I could code the function to achieve the desired result.
"""All numbers divisible by 3 and 5 are divisible by 15
This is an interator generator so nothing is stored in memory"""
def fizzBuzz(numbers):
for i in numbers:
if i % 15 == 0:
yield "FizzBuzz"
elif i % 5 == 0:
yield "Buzz"
elif i % 3 == 0:
yield "Fizz"
else:
yield str(i)
print " ".join(fizzBuzz(range(1,31)))
"""Here we append an empty string with either Fizz or Buzz or both when appropriate
Then we return that string, unless it is empty, and then n is returned"""
for n in range(1, 31):
s = ""
if n % 3 == 0:
s += "Fizz"
if n % 5 == 0:
s += "Buzz"
print s or n,
"""This is essentially the same code as above, however I have now simplified it
to avoid creating a variable to store the string inside each time a loop is run"""
for n in range(1, 31):
print("Fizz"*(n % 3 == 0) + "Buzz"*(n % 5 == 0) or n),
This last solution seems to take up the least code, so I will combine this into the function:
def fizzBuzz():
while True:
try:
x = abs(int(input("Enter a number up to which you would like to 'FizzBuzz': ")))
break
except NameError:
print("Error! You must enter a numeric digit, for example: 6, 93, 529 etc.")
nums = range(1,x+1)
for n in range(1, 31):
print("Fizz"*(n % 3 == 0) + "Buzz"*(n % 5 == 0) or n),
fizzBuzz()