FizzBuzz Python Program

 

 

FizzBuzz Program in Python

This Python program prints the numbers from 1 to 100. For multiples of three, it prints “Fizz” instead of the number, and for multiples of five, it prints “Buzz”. For numbers which are multiples of both three and five, it prints “FizzBuzz”.

Program Structure and Explanation

The program uses a simple loop and conditional statements to achieve the desired output. Below is the program along with explanations:


# Define the main function
def fizzbuzz():
    """
    This function prints numbers from 1 to 100.
    For multiples of three, it prints 'Fizz'.
    For multiples of five, it prints 'Buzz'.
    For multiples of both three and five, it prints 'FizzBuzz'.
    """
    # Loop from 1 to 100
    for i in range(1, 101):
        # Check if the number is a multiple of both 3 and 5
        if i % 3 == 0 and i % 5 == 0:
            print("FizzBuzz")
        # Check if the number is a multiple of 3
        elif i % 3 == 0:
            print("Fizz")
        # Check if the number is a multiple of 5
        elif i % 5 == 0:
            print("Buzz")
        # If the number is not a multiple of 3 or 5, print the number
        else:
            print(i)

# Call the main function
if __name__ == "__main__":
    fizzbuzz()

Explanation

  • Defining the Function: The fizzbuzz function is defined to encapsulate the logic of the program.
  • Loop from 1 to 100: The for loop iterates over the range of numbers from 1 to 100 (inclusive).
  • Conditional Checks:
    • The if statement checks if the current number i is divisible by both 3 and 5 using the modulus operator %.
    • If the number is divisible by both 3 and 5, it prints “FizzBuzz”.
    • Next, the elif statement checks if the number is divisible by 3 and prints “Fizz” if true.
    • Another elif statement checks if the number is divisible by 5 and prints “Buzz” if true.
    • If none of the above conditions are met, the number itself is printed.
  • Calling the Function: The function fizzbuzz is called within the if __name__ == "__main__" block to ensure it runs when the script is executed directly.

 

Leave a Reply

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