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