2017-08-10 221 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()