图案
重复提示用户输入的一般模式是:
# 1. Many valid responses, terminating when an invalid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
else:
handle_invalid_response()
break
我们使用无限循环while True:
而不是重复我们的get_user_input
函数两次(hat tip https://stackoverflow.com/a/23294659/135978).
如果您想检查相反的情况,只需更改break
:
# 2. Many invalid responses, terminating when a valid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
break
else:
handle_invalid_response()
如果您需要循环工作,但在用户提供无效输入时警告用户,那么您只需要添加一个测试来检查quit
某种且唯一的命令break
there:
# 3. Handle both valid and invalid responses
while True:
user_response = get_user_input()
if test_that(user_response) is quit:
break
if test_that(user_response) is valid:
do_work_with(user_response)
else:
warn_user_about_invalid_response()
将模式映射到您的具体案例
您想要提示用户为您提供一个少于十个字符的句子。这是模式#2 的一个实例(许多无效响应,只需要一个有效响应)。将模式 #2 映射到您的代码中,我们得到:
# Get user response
while True:
sentence = input("Please provide a sentence")
# Check for invalid states
if len(sentence) >= 10:
# Warn the user of the invalid state
print("Sentence must be under 10 characters, please try again")
else:
# Do the one-off work you need to do
print("Thank you for being succinct!")
break