FizzBuzz (One Number)

FizzBuzz (One Number)

A classic. Write a function that classifies a single number:

fizzbuzz_one(n)
  • If n is divisible by both 3 and 5, return "FizzBuzz".
  • Else if n is divisible by 3, return "Fizz".
  • Else if n is divisible by 5, return "Buzz".
  • Otherwise, return n as a string.

Examples

fizzbuzz_one(15)  // → "FizzBuzz"
fizzbuzz_one(9)   // → "Fizz"
fizzbuzz_one(10)  // → "Buzz"
fizzbuzz_one(7)   // → "7"

Walkthrough

Thinking it through

The classic trap here is checking n % 3 == 0 and n % 5 == 0 separately before the combined case — if you did that, 15 would hit the n % 3 == 0 branch first and return "Fizz", never getting a chance to also register as divisible by 5.

def fizzbuzz_one(n):
    if n % 15 == 0:
        return "FizzBuzz"
    elif n % 3 == 0:
        return "Fizz"
    elif n % 5 == 0:
        return "Buzz"
    else:
        return str(n)

Checking n % 15 == 0 first sidesteps the ordering problem entirely: a number divisible by both 3 and 5 is, by definition, divisible by 15 (their least common multiple). Handling that case up front means the elif branches underneath only ever see numbers that are divisible by exactly one of 3 or 5 (or neither) — matching the earlier lesson's pattern of ordering elif chains from most-specific to least-specific.

The final else: return str(n) matters too: n is an int, but the function needs to return a str in every branch for the caller to treat the result consistently (you can't concatenate an int with the "Fizz"/"Buzz" strings elsewhere without converting it).

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.