I'm asking users a series of questions and recording their answers. My question-askers check the formatting of these answers and return a flag if a user inputs something strange (like my name is 102
).
I'd like this program to break out of the question set if any of these answers are wrong, right away. I'm attempting to use a while loop to do this but it is clear to me that this while loop only checks the value of the flag at the end of each loop, so it won't restart the question asking process until the block of questions are done.
Note the `letter' variable is a surrogate for user input in this example. This is not how the code actually looks.
def string_checker(letter, output):
if type(letter) != str:
print('You did not give me a string!')
output = 1
return output
output = 0
# this should go until question 3, when the user makes a mistake
while output == 0:
# question 1
letter = 'bob'
print(letter)
output = string_checker(letter, output)
# question 2
letter = 'aldo'
print(letter)
output = string_checker(letter, output)
# question 3 --- user gets this wrong
letter = 1
print(letter)
output = string_checker(letter, output)
# question 4
letter = 'angry'
print(letter)
output = string_checker(letter, output)
# but it seems to ask question 4, regardless
print('done!')
Is there a way for me to modify this code so that question 4
is never asked?
UPDATED CODE BASED ON JASPER'S ANSWER
Building on Jasper's answer with a full solution... this modification to my problem solved it. By raising a ValueError inside of the checking function, the try block fails immediately and we can escape from main using a return.
def string_checker(letter):
if type(letter) != str:
raise ValueError
def main():
# this should go until question 3, when the user makes a mistake
try:
# question 1
letter = 'bob'
print(letter)
string_checker(letter)
# question 2
letter = 'aldo'
print(letter)
string_checker(letter)
# question 3 --- user gets this wrong
letter = 1
print(letter)
string_checker(letter)
# question 4
letter = 'angry'
print(letter)
string_checker(letter)
# we make a mistake at question 3 and go straight to here
except ValueError as ve:
print('You did not give me a string!')
return 'oops'
# exit
return 'done'