I have this function that calls itself:
def get_input():
my_var = input('Enter "a" or "b": ')
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
else:
return my_var
print('got input:', get_input())
Now, if I input just "a" or "b", everything works fine:
Type "a" or "b": a
got input: a
But, if I type something else and then "a" or "b", I get this:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
I don't know why get_input()
is returning None
since it should only return my_var
. Where is this None
coming from and how do I fix my function?
return Dat_Function()
when calling it recursively. – Jemymy_var != "a" and my_var != "b"
condition would bemy_var not in ('a', 'b')
– Breakupwhile
loop makes more sense. See Asking the user for input until they give a valid response. – Readytowearreturn
would break out of the loop. In general, however, this is the same problem as if you were trying to call any other function, rather than using recursion. It is also a commonly asked quesiton, with a reference duplicate here: How can I usereturn
to get back multiple values from a loop? Can I put them in a list? – Readytowear