2016-05-14 36 views
0

我想做一個for循環,不斷要求每次有不同名稱的新輸入,所以它會是q1,q2,q3,q4等。這樣我就不必繼續輸入更多的信息或一定數量的他們。如何創建一個循環來重複輸入新的輸入?

我也需要它在每個輸入上打印相同的問題。

「您想添加什麼湯?」

感謝您的幫助,我可以得到。

+0

使用字典的名稱。 – cdarke

+0

您的問題是關於python中這樣一個for循環的結構,還是您在問如何存儲不確定數量的答案? – CorbinMc

+0

我想存儲不確定數量的答案,但它需要是每個答案的單獨問題。 @CorbinMc – BlizzardGizzard

回答

1

爲了存儲對您的問題的回答數量不確定的數量,您應該使用一個列表。在開始for循環之前創建一個空列表,並使用list.append()函數在列表中添加每個答案。

列表具有相對高效的內存優勢。使用字典要求您保存鍵值對(使用兩倍的內存),而不是簡單地依賴內存中值的順序。

示例代碼可能是這樣的:

n = 10 # the number of iterations to perform 
answers = list() 
for i in range(0, n): 
    answers.append(input("question?")) 

print(answers[2]) #this would print the third entered answer 
print(answers[4]) #this would print the fourth entered answer 
+0

非常感謝! ^^^^ – BlizzardGizzard

1

很簡單,但你可能不需要for循環。下面是一個使用字典一個簡單的例子:

answers = {} 
count = 1 

while True: 
    ans = input("What would you like to add to your soup? ") 
    if ans.lower() == 'nothing': 
     break 

    answers['q' + str(count)] = ans 
    count += 1 

print(answers) 

我們有一個無限循環(while True),但是當用戶輸入「無」一個突破。你不必這樣做,但在大多數應用中,你需要類似的東西。

採樣運行:

What would you like to add to your soup? carrots 
What would you like to add to your soup? peas 
What would you like to add to your soup? chicken 
What would you like to add to your soup? noodles 
What would you like to add to your soup? nothing 
{'q4': 'noodles', 'q2': 'peas', 'q1': 'carrots', 'q3': 'chicken'} 

使用字典,你可以使用任何你喜歡的名字,但我不知道如果你真的需要這些名字,爲什麼你需要他們。通常只需將答案附加到列表就足夠了。

answers = [] 

while True: 
    ans = input("What would you like to add to your soup? ") 
    if ans.lower() == 'nothing': 
     break 

    answers.append(ans) 

print(answers) 

正如您所看到的,代碼非常簡單,而且很簡單。示例的輸出爲:

['carrots', 'peas', 'chicken', 'noodles'] 
+0

嗯,我使用它作爲我必須在學校寫的程序,在這個程序中我需要得到答案並將它們放入一個.csv文件中,然後在另一行上打印,並在其旁邊添加兩行信息。像藝術家的名字 - 他們在舞臺上多久 - 他們得到多少報酬。 – BlizzardGizzard

+0

我也不知道這本詞典中的大部分內容。 – BlizzardGizzard

+0

你可能想要列表解決方案,然後保持簡單(KISS)。 – cdarke

1

的變化上使用列表中的主題:

answers = [] 
while True: 
    whom = raw_input("Who is on stage ") 
    if whom == "": 
     break 
    duration = raw_input("For how many minutes ") 
    answers.append((whom,duration)) 
for i in answers: 
    print i[0], "was on stage for", i[1], "minutes"