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)
只是不使用'break'? (取決於腳本的其餘部分)。 – 2012-03-07 21:20:02
@Felix:儘管如此,他仍然需要將他的實際代碼包裝到'else'分支中,這可以通過使用「continue」來防止。 – 2012-03-07 21:21:00