如果第一次输入无效,则提示用户输入其他内容 [英] Prompt the user to input something else if the first input is invalid
本文介绍了如果第一次输入无效,则提示用户输入其他内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对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?
推荐答案
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屋!
查看全文