python中的fizz buzz游戏

时间:2018-01-30 18:26:05

标签: python fizzbuzz

编写一个名为fizzBu​​zz的简单函数,它接受一个正整数,并根据以下内容返回'fizz','buzz','fizzbuzz'或它收到的参数:

Returns ‘fizz’ if the argument is divisible by 3
Returns buzz if the argument is divisible by 5
Returns ‘fizzBuzz’ if the argument is divisible by 3 and 5
Returns the argument itself if it is NOT divisible by 3 or 5
Returns exactly 'Invalid Argument' when an invalid argument is passed.

实施例: 输入输出
3" fizz"
5"嗡嗡声"
15" fizzBu​​zz"

我尝试了这段代码,但它没有用

def fizz_buzz(n):
    n = []
    for nums in n:
        if nums % 5 == 0 and nums % 3 == 0:
            print("fizz buzz")
        elif nums % 3 == 0:
            print("fizz")
        elif nums % 5 == 0:
            print("buzz")
        elif nums % 3 != 0 and nums % 5 != 0:
            print(nums)
        else:
            print("invalid arguement")

6 个答案:

答案 0 :(得分:1)

我认为最简单的方法:

def fizz_buzz(input):
    if (input % 3 == 0) and (input % 5 == 0):
        return 'FizzBuzz'
    if input % 3 == 0:
        return 'Fizz'
    if input % 5 == 0:
        return 'Buzz'
    return input

打印(fizz_buzz(3))

PS:使用任意数字更改print(fizz_buzz(3))进行测试

答案 1 :(得分:0)

这是你可以采用的一种方式; P

from itertools import islice,count

targets = [3,5,15,22]
for target_value in targets:
    fizzbuzz = ("".join("BzuzzizF"[::2 * j] for j in (-1, 1) if 1 > i % (4 + j)) or i for i in count(1) )
    print(target_value,"=",next(islice(fizzbuzz,target_value-1,target_value+3)))

答案 2 :(得分:0)

我这样做是为了写。它使用字典使其易于修改。

multiples = {3 : 'Fizz', 5 : 'Buzz'}
for i in range (1, 101):
    output = ''
    for j in multiples.keys():
        if i % j == 0:
            output += str(multiples.get(j))    
    if output == '':
        output = str(i)

    print (output)

如果将字典更改为类似multiples = {3 : 'Fizz', 5 : 'Buzz', 7 : 'Fuzz'}的字典,它将仍然有效

答案 3 :(得分:0)

因为必须成为列表,所以我会这样做:

def fizz_buzz(n):
    for nums in n:
        if nums % 5 == 0 and nums % 3 == 0:
            print("fizz buzz")
        elif nums % 3 == 0:
            print("fizz")
        elif nums % 5 == 0:
            print("buzz")
        elif nums % 3 != 0 and nums % 5 != 0:
            print(nums)
        else:
            print("invalid argument")


my_list = []

while True:
    user_input = input('Enter the Number: ')
    if user_input != 'exit':
         my_list.append(int(user_input))
    else:
        break

fizz_buzz(my_list)

在底部部分,我生成一个列表。您没有提供有关从何处获取电话号码的任何信息...因此请在需要时使用。但是fizz_buzz函数现在肯定可以工作

答案 4 :(得分:0)

这是您的代码

def fizz_buzz(n):
   
  if (n % 3 == 0) and (n % 5 == 0):
    return 'FizzBuzz'
    
  if n % 3 == 0:
    return 'Fizz'

  if n % 5 == 0:
    return 'Buzz'

  return n

print(fizz_buzz(6))

答案 5 :(得分:-1)

def fizzbuzz(n):

    if n % 3 == 0 and n % 5 == 0:
        print('FizzBuzz')
    elif n % 3 == 0:
        print('Fizz')
    elif n % 5 == 0:
        print('Buzz')
    else:
        return str(n)

n=int(input("Enter number:"))

fizzbuzz(n)

这有效...