Chapter 20: Exploring FizzBuzz in Python

Chapter 20: Exploring FizzBuzz in Python

FizzBuzz is a classic programming problem. Here are different ways to tackle it in Python:

1. Using if-elif Statements:

for num in range(1, 101):
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz")
    elif num % 3 == 0:
        print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)
        
Article content

2. Using a Dictionary for Mapping:

fizz_buzz_dict = {3: "Fizz", 5: "Buzz"}
for num in range(1, 101):
    result = ""
    for key in fizz_buzz_dict.keys():
        if num % key == 0:
            result += fizz_buzz_dict[key]
    print(result or num)        
Article content

3. Using List Comprehension and join():

for num in range(1, 101):
    output = [word for div, word in [(3, "Fizz"), (5, "Buzz")] if num % div == 0]
    print("".join(output) or num)        
Article content

4. Using a Ternary Conditional Expression:

for num in range(1, 101):
    print("Fizz" * (num % 3 == 0) + "Buzz" * (num % 5 == 0) or num)        
Article content

5. Using a dict.get() Method:

for num in range(1, 101):
    output = ""
    output += "Fizz" if num % 3 == 0 else ""
    output += "Buzz" if num % 5 == 0 else ""
    print(output or num)        
Article content

Each method accomplishes the FizzBuzz task. Pick the one that resonates with you and enhances your Python skills. Happy coding! 🚀🐍 #PythonProgramming #LoveLogicByte

To view or add a comment, sign in

More articles by Loveleen Sharma (philomath)

Explore content categories