【问题标题】:Prompt the user to input something else if the first input is invalid [duplicate]如果第一个输入无效,则提示用户输入其他内容[重复]
【发布时间】:2012-03-07 21:18:10
【问题描述】:

我对 Python 很陌生,所以请原谅我的新问题。我有以下代码:

[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]

如果我愿意,而不是中断循环并退出程序,而是将用户返回到原始提示,直到他们输入有效数据,我会写什么而不是 break?

【问题讨论】:

  • 只是不要使用break? (取决于脚本的其余部分)。
  • @Felix:不过,他仍然需要将他的实际代码包装到 else 分支中,这可以通过使用 continue 来避免。

标签: python input


【解决方案1】:

要继续下一个循环迭代,您可以使用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.")

【讨论】:

  • 正如 Niklas 指出的,值得注意的是,如果使用 continueelse 条件也可以被删除。
  • @Sven Marnach raw_input 中的“PROMPT”有什么用?请清除它,我也是 python 中的新手
  • @VarunChhangani:等待用户输入前打印的提示;见documentation
【解决方案2】:
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)

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多