0

我如何让 python 根据输入响应提出相同的问题。假设我问以下问题,您今天要配置多少组?用户回复 10。我希望 python 允许用户输入 10 个不同的组名,这样 python 会要求它输入 10 个输入。根据输入,我会采取其余的车。

4

3 回答 3

0

您可以只使用 for 循环(或者,如果您愿意,可以使用列表推导):

# ignoring error handling
numGroups = int(raw_input('How many groups would you like to configure today? '))

names = [raw_input('Name for group %d: '%n) for n in range(numGroups)]
于 2013-06-13T03:08:58.810 回答
0

如果您使用 python 3.x ,请更改raw_inputinput

n = int(raw_input('How many groups would you like to configure today? '))
for i in range(n):
    group = raw_input('Group {}: '.format(i+1))
    # Do something with group...
于 2013-06-13T03:09:53.430 回答
0

就像是

resp = raw_input('How many groups would you like to configure today? ')
try:
    num = int(resp)
except ValueError as e:
    # Handle error

groups = []
for i in range(num):
    resp = raw_input('Enter group name: ')
    groups.append(resp)

# The rest (at this point, the group names will be in the list "groups")

...应该管用。主要部分是raw_input将响应推送到带有 的列表中append。此外,请确保您处理用户输入“二”之类的内容或仅按 Enter 而不是数字(使用try/ except)的情况。

于 2013-06-13T03:10:53.350 回答