如果第一个输入无效,则提示用户输入其他内容 [英] Prompt the user to input something else if the first input is invalid

查看:24
本文介绍了如果第一个输入无效,则提示用户输入其他内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very new to Python, so forgive my newbish question. I have the following code:

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

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

If I wanted to, instead of breaking the loop and quitting the program, send the user back to the original prompt until they input valid data, what would I write instead of break?

推荐答案

要继续下一个循环迭代,您可以使用 continue 声明.

To go on with the next loop iteration, you can use the continue statement.

我通常会将输入分解为专用函数:

I'd usually factor out the input to a dedicated function:

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.")

这篇关于如果第一个输入无效,则提示用户输入其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆