The pattern
The general pattern for repeatedly prompting for user input is:
# 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
We use the infinite loop while True:
rather than repeating our get_user_input
function twice (hat tip).
If you want to check the opposite case, you simply change the location of the 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()
If you need to do work in a loop but warn the user when they provide invalid input then you just need to add a test that checks for a quit
command of some kind and only 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()
Mapping the pattern to your specific case
You want to prompt a user to provide you a less-than-ten-character sentence. This is an instance of pattern #2 (many invalid responses, only one valid response required). Mapping pattern #2 onto your code we get:
# 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