I am a python noob and was hoping someone could point me in the right direction here.
I am trying to get user input and only accepting upper and lower case letters.
If anything else is entered then I want to ask the user again for valid input (a letter).
My code works (to a degree) - if the correct value is entered it works as expected, but if invalid values are entered it asks the question again but now even if valid values are entered it requires the value entered in as many times as there were wrong answers.
I understand there may be better ways to do what I want (and I have a different working solution below but my curiosity is why this script behaves as it does)
import string
def get_guess():
lower_letters = list(string.ascii_lowercase)
while True:
try:
guess = input('Guess a letter: ')
if guess.lower() in lower_letters:
return guess
else:
get_guess()
except:
print("That's not a valid option!")
letter = get_guess()
print(letter)
To help explain here is the code in action:
I know I can replace that code with the code below and get the result I am after but can you explain why the top code is doing what it is - once again if this is an obvious noob question I just couldn't let it go.
Working code:
import re
while 1:
inputString = input()
if re.match(r"^[A-Z,a-z]$", inputString):
print("Input accepted")
break
else:
print("Bad input, please try again")
Please also feel free to point me to any other resource if there is a better way to get the same result rather than the 2 snippets I have provided - I am always willing to learn.
Thank you all in advance.