Salah
Salah

Reputation: 41

Python: Recursion, I keep getting the wrong value, what I can do?

def answer(): 
    if True:
        ans = raw_input('Enter y/n:')

        if ans != "y" and ans != "n":
            print "Try again"
            answer()
        elif ans == "n":
            return False
        elif ans == "y":
            return True
if answer():
    print "It's working!, you entered Y"
else:
    print "You entered N"

When I execute this code, I press Enter several times or enter wrong letters, then I enter y, I always get "You entered N" instead of "It's working!, you entered Y" .

I can't figure out what's the problem, please help me.

Upvotes: 0

Views: 247

Answers (2)

jbaiter
jbaiter

Reputation: 7109

You don't really need recursion in this case, just use an infinite loop and don't return if the answer is not "y" or "n":

def answer(): 
    while True:
        ans = raw_input('Enter y/n:')
        if not ans or ans not in "yn":
            print "Try again"
        else:
            return ans == "y"  # This is more succinct

if answer():
    print "It's working!, you entered Y"
else:
    print "You entered N"

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213311

You are discarding the return value of your function in the if block. You should change it to:

if ans != "y" and ans != "n":
    print "Try again"
    return answer()

If you don't return the value, your function will return None, which will be evaluated as False on the outer if. Also, there is no need of if True: inside your function.

P.S: Please avoid using recursion for this task. You can easily do this with a while loop, which iterates till the user doesn't pass correct input, and breaks as soon as succeeds. Also, give user a certain number of attempts to pass correct inputs, to avoid infinite loop.

Upvotes: 9

Related Questions