问题: Write a function called fizz_buzz(n) which takes as a parameter an integer, n. If n is divisible by 3 the function should return “fizz”; if n is divisible by 5 the function should return “buzz” and if the function is divisible by both 3 and 5, the function should return “fizz-buzz”. Otherwise the function should just return the value n.
翻译: 编写一个名为 fizz_buzz(n) 的函数,该函数将整数 n 作为参数。如果 n 可以被 3 整除,则函数应输出 “fizz”; 如果 n 可以被 5 整除,则函数应输出“buzz”,如果函数可同时被 3 和 5 整除,则该函数应输出“fizz-buzz”。否则,该函数应仅输出值 n。
这道题简单可以理解成:当输入能被3,5同时除尽的数字时,输出与只能被3,5单独除尽时不同的符号。
Python代码如下:
def fizz_buzz (n):
n = int(input("Please Enter a number:"))
if n % 3 == 0 and n % 5 == 0:
print("fizz-buzz")
elif n % 5 == 0:
print("buzz")
elif n % 3 == 0:
print("fizz")
else:
print(n)
fizz_buzz(any)
本人刚开始被问题限制了思路,把fizz,buzz的运算放在首先,导致模拟运算fizz-buzz (能同时被3和5除尽)的情况时先输出了fizz。这时如果打破顺序,优先判断fizz-buzz的情况是否成立,就可以轻松应对所有情况。
输出结果如下:
Please Enter a number: 6
fizz
Please Enter a number: 10
buzz
Please Enter a number: 15
fizz-buzz
Please Enter a number: 16
16
感谢阅读,欢迎指教