Python – Challenge: FizzBuzz

By | 28/07/2020

In this post, we will see how to resolve FizzBuzz using Python.
We will create a function that takes a number as input and it will return “Fizz“, “Buzz” or “FizzBuzz“.
The rules are:

  • If the number is a multiple of 3 the output should be “Fizz”.
  • If the number is a multiple of 5, the output should be “Buzz”.
  • If the number is a multiple of both 3 and 5, the output should be “FizzBuzz”.
  • If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below.
  • The output should always be a string even if it is not a multiple of 3 or 5

EXAMPLES:
Fizz_buzz(3) -> “Fizz”
Fizz_buzz(5) -> “Buzz”
Fizz_buzz(15) -> “FizzBuzz”
Fizz_buzz(4) -> “4”

SOLUTION:
We open Visual Studio Code and we create a file called FizzBuzz:

[FIZZBUZZ.PY]

# we import sys in order to close the application if the input isn't a number
import sys

# definition of the function FizzBuzz
def FizzBuzz(num):
    if num%3 == 0 and num%5 !=0:
        return "Fizz"
    elif num%5 == 0 and num%3 != 0:
        return "Buzz"
    elif num%3 == 0 and num%5 == 0:
        return "FizzBuzz"
    else:
        return str(num)


# Input
valInput = input("Insert the value: ")
 
# Input verification
if valInput.isnumeric()==False:
    print("Value must be integer")
    sys.exit()

# Print the result
print(FizzBuzz(int(valInput)))



If we run the application, this will be the result:



Leave a Reply

Your email address will not be published. Required fields are marked *