2017-08-10 132 views
0

我是新来的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() 

回答

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

尝试把名字输入外循环是这样的:

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) 
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() 

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

1

由于输入在Python中被视为字符串,因此您必须显式地对输入进行类型转换才能将其用于迭代! 所以使用range(int(times))或者在你输入的时候施放它。

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()