如何创建一个循环来一次又一次地进行新的输入



我想创建一个for循环,不断要求每次都有不同名称的新输入,因此它将是q1q2q3q4等。这样我就不必不断进行更多的输入或指定数量的输入。

我还需要它在每个输入上打印相同的问题。

"你想在汤里加什么?"

谢谢你给我的任何帮助。

为了存储对问题的不确定数量的回答,您应该使用列表。在开始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

非常简单,但您可能不需要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),但当用户输入"Nothing"时会爆发。你不必有这个,但在大多数应用程序中,你都需要这样的东西。

样品运行:

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']

使用列表的主题变体:

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"

相关内容

最新更新