Python输入循环取决于输入的数字

时间:2013-06-13 03:06:59

标签: python

如何让python根据输入响应提出相同的问题。假设我问下面的问题,您今天要配置多少个组?用户响应10.我想让python然后允许用户输入10个不同的组名,因此python会要求它输入10个。根据输入,我将采取其余的车。

3 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:0)

如果您使用python 3.x

,请将raw_input更改为input
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...

答案 2 :(得分: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的列表。此外,请确保您处理用户输入“两个”之类的情况,或者只按下输入而不是数字(使用try / except)。