📜  python中的fizzbuzz程序(1)

📅  最后修改于: 2023-12-03 15:19:26.897000             🧑  作者: Mango

FizzBuzz in Python

FizzBuzz is a classic programming task that is often used during interviews to assess a programmer's basic coding skills. The task is to write a program that prints the numbers from 1 to 100. But for multiples of 3, print "Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers that are multiples of both 3 and 5, print "FizzBuzz".

Here's an implementation of the FizzBuzz program in Python:

def fizzbuzz():
    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)

fizzbuzz()

In this implementation, we define a function called fizzbuzz that uses a for loop to iterate through the numbers from 1 to 100. We use the modulo operator (%) to check if a number is divisible by 3, 5, or both.

If a number is divisible by both 3 and 5, we print "FizzBuzz". If it's only divisible by 3, we print "Fizz". If it's only divisible by 5, we print "Buzz". Otherwise, we print the number itself.

The function is then called to execute the FizzBuzz program.

By running the code, you will see the output that follows the FizzBuzz rules:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...
98
Fizz
Buzz

This implementation of FizzBuzz demonstrates basic programming concepts such as loops, conditions, and modulo arithmetic. It can be easily customized to change the range of numbers or modify the strings that are printed. FizzBuzz serves as a good exercise to practice problem-solving and improve coding skills.