2012-03-07 62 views
0

我很新到Python,所以原谅我newbish问题。我有以下代码:提示用户输入别的东西,如果第一输入无效

[a while loop starts] 

print 'Input the first data as 10 characters from a-f' 

input1 = raw_input() 
if not re.match("^[a-f]*$", input1): 
    print "The only valid inputs are 10-character strings containing letters a-f" 
    break 
else: 
[the rest of the script] 

如果我想,而不是打破循环和退出程序,向用户发送回原来的提示,直到输入有效数据,我会怎么写的,而不是休息时间吗?

+4

只是不使用'break'? (取决于脚本的其余部分)。 – 2012-03-07 21:20:02

+0

@Felix:尽管如此,他仍然需要将他的实际代码包装到'else'分支中,这可以通过使用“continue”来防止。 – 2012-03-07 21:21:00

回答

6

到下一个循环迭代下去的话,你可以使用continue statement

我平时分解出输入到专门的功能:

def get_input(prompt): 
    while True: 
     s = raw_input(prompt) 
     if len(s) == 10 and set(s).issubset("abcdef"): 
      return s 
     print("The only valid inputs are 10-character " 
       "strings containing letters a-f.") 
+0

正如Niklas指出的那样,值得注意的是,如果使用“continue”,那么'else'条件也可以被删除。 – 2012-03-07 21:23:08

+0

@Sven Marnach在raw_input中使用“PROMPT”有什么用?请清除它,我也是新的python – 2014-04-15 05:25:30

+1

@VarunChhangani:这是等待用户输入之前打印的提示;请参阅[documentation](https://docs.python.org/2.7/library/functions.html#raw_input)。 – 2014-04-15 10:47:00

0
print "Input initial data. Must be 10 characters, each being a-f." 
input = raw_input() 
while len(input) != 10 or not set(input).issubset('abcdef'): 
    print("Must enter 10 characters, each being a-f." 
    input = raw_input() 

轻微替代:

input = '' 
while len(input) != 10 or not set(input).issubset('abcdef'): 
    print("Input initial data. Must enter 10 characters, each being a-f." 
    input = raw_input() 

或者,如果你想打破它在一个函数(此功能是矫枉过正用于该用途,而是一种特殊情况下的全功能是次优的IMO):

def prompt_for_input(prompt, validate_input=None, reprompt_on_fail=False, max_reprompts=0): 
    passed = False 
    reprompt_count = 0 
    while not (passed): 
     print prompt 
     input = raw_input() 
     if reprompt_on_fail: 
      if max_reprompts == 0 or max_reprompts <= reprompt_count: 
       passed = validate_input(input) 
      else: 
       passed = True 
     else: 
      passed = True 
     reprompt_count += 1 
    return input 

这种方法可以让你定义你的验证器。你可以这样称呼它:

def validator(input): 
    return len(input) == 10 and set(input).subset('abcdef') 

input_data = prompt_for_input('Please input initial data. Must enter 10 characters, each being a-f.', validator, True)