python – Fizzbuzz(将输出转换为字符串?)

新来的,希望我可以帮助我.基本上,我的任务是用
Python写一个fizzbuzz程序,到目前为止除了我收到的一些反馈之外这么好.

现在我必须确保程序的输出水平,并且不会在新行上垂直打印.从我的理解和我的讲师提示,我需要转换函数来生成字符串并删除打印语句.

代码如下:

def fizzbuzz1 (num):
    for num in range(1, num): 
        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)

def main (): 
    while True: #Just to keep my program up and running while I play with it
    num = input ("please type a number: ") #
    num = int (num)
    print ("Please select an type what option you wish to try: A) Is this Fizz or Buzz? B) Count saying fizz/buzz/fizzbuzz") 
    opt = input ("Please type A or B and press enter: ")
    if opt == "A": 
        fizzbuzz(num)
    elif (opt == "a")
        fizzbuzz(num)
    elif (opt == "B"):
        print (fizzbuzz1(num))
    elif (opt == "b"):
        print (fizzbuzz1(num))

main ()

我尝试了很多东西,而且我的讲师似乎对帮助我没什么兴趣. Womp.我被推荐回顾这个练习我是用这段代码玩的:

def func(num):
value = ‘’
for x in range(...):
    if   .... == .... :
        value += str(x) + ‘, ‘
return value[…]# You need to remove the last comma and the space

当我使用此代码时,我会在屏幕上显示数字.但是对于我的生活,我似乎无法将我所写的内容与其中的元素结合起来.我哪里误入歧途?

感谢您提供的任何建议/帮助.如果您确实选择回复,请为我保持尽可能简单.

干杯.

更新:感谢大家的建议,很多我不知道尝试的thimgs!

我还在这里找到了一个帖子:Can’t figure out how to print horizontally in python?

哪个有类似问题的答案.

最佳答案 如果使用Python 3.x,请尝试不使用新行进行打印

def fizzbuzz1 (num):
for num in range(1, num): 
    if (num%3 == 0) and (num%5 == 0): 
        print("Fizzbuzz ", end="")
    elif ((num % 3) == 0):
        print("Fizz ", end="")
    elif ((num % 5) == 0):
        print("buzz ", end="")
    else:
        print ( str(num) + " ")
print(" ")
点赞