2012-03-07 24 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) 
相關問題