Python循环问题

时间:2017-08-10 15:10:03

标签: python

我是python的新手,所以我想创建一些简单的程序来学习更多。

我需要帮助的这个程序是为了执行以下步骤:

  • 要求提供姓名
  • 要求多次重复歌曲中的内容
  • 按给定的次数打印给定的歌词

但我有一个问题,不重复,我做错了什么?

def bSong(name):
    print('Happy Birthday to you!')
    print("Happy birthday dear " + name + "")

def main():
    times = int(input('Enter the number of times to repeat: '))
    for i in range(times):
        name = input("What is the name of the birthday person: ")
        bSong(name)

main()

4 个答案:

答案 0 :(得分:1)

您需要更改:

def main():
    times = int(input('Enter the number of times to repeat: '))
    for i in range(times):
        name = input("What is the name of the birthday person: ")
        bSong(name)

为:

def main():
    times = int(input('Enter the number of times to repeat: '))
    name = input("What is the name of the birthday person: ")
    for i in range(times):
        bSong(name)

就目前而言,您要求用户多次输入名称。

答案 1 :(得分:1)

尝试将名称输入放在循环之外,如下所示:

def bSong(name):
    print('Happy Birthday to you!')
    print("Happy birthday dear " + name + "")

def main():
    name = input("What is the name of the birthday person: ")
    times = int(input('Enter the number of times to repeat: '))
    for i in range(times):
        bSong(name)

答案 2 :(得分:0)

如果您想要读取一次名称,请将name = input("What is the name of the birthday person: ")放在for循环之外。

def bSong(name):
    print('Happy Birthday to you!')
    print("Happy birthday dear " + name + "")

def main():
    times = int(input('Enter the number of times to repeat: '))
    name = input("What is the name of the birthday person: ")
    for i in range(times):
        bSong(name)




main()

这是你期待的还是别的什么?

答案 3 :(得分:0)

我希望这能解决你在python 2.7中的问题

def bSong(name):
    print('Happy Birthday to you!') 
    print("Happy birthday dear " + name + "")
def main(): 
    times = int(input('Enter the number of times to repeat: ')) 
    for i in range(times): 
        name = raw_input("What is the name of the birthday person: ")
        bSong(name)
main()