New to Python, I wanted to create a function that prompts the user for input and checks if it's an acceptable input (there's a list of ok inputs). If acceptable - returns the input. If not - prompts the user again until he provides an acceptable input.
This is what I used:
def get_choice():
possible_choices = ["option1","option2","option3","option4"]
choice = raw_input("Please enter your choice: ").lower()
if choice not in possible_choices:
print "Sorry, please try again"
return get_choice() # if not an acceptable answer - run the function again
return choice
now, this works. What I'm wondering about is the return command when the if condition is True. Intuitively I didn't place return there, just called the function again, and it would indeed run it again if the user didn't input an acceptable entry. However, the function itself would return the original value the user inputted, acceptable or not. Only when I added return before calling the function again, it started to work fine.
Can anyone explain why that is? It 'makes sense' that when calling the function again, choice would now point to the new user input, not the first one.
I got the idea to add the return there from Abrixas2's answer to this question:
Python getting user input errors.
However, over here: Continually prompting user for input in Python, part of audionautics's answer relates to a similar issue and he suggests this function:
def get_input_number():
num = int(raw_input("Enter a positive integer no greater than 42 "))
if num <= 0 or num > 42:
print "Invalid input. Try again "
get_input_number()
else:
return num
Obviously the input needs to be validated by other criteria than me, but you get that the nature of the problem is the same. He doesn't have a return statement there before calling the function again. I tried running this code along with:
test = get_input_number()
print test
to print the result, and it returned nothing. The reason I bring it up is that it still got 3 upvotes (most upvotes for that question) so I didn't want to dismiss it all together when I'm researching this issue.
Anyway, bottom line, can someone please explain what's the right way to go about it and why did my function without the return statement inside the if condition returned the first value the user inputted?
Thanks :D