0

I'm working with functions and arguments and even with a simply code when function is called inside I'm getting error like: line 7, in question if ask == 'yes': RecursionError: maximum recursion depth exceeded in comparison

If I type in: Yes in answer, yes it works fine but when I type in: no and function is called belowe else statement I get error: line 5, in question if ask == 'yes': RecursionError: maximum recursion depth exceeded in comparison

I'm doing something wrong? BTW I googled the problem and doesn't solve problem sys.setrecursionlimit(5000) and still getting error:

ask = input("Are you OK?:").lower()
asked = ask
def question(n):

    if ask == 'yes':
        return n

    else:
        question(n)

print (question(asked))

I tried another way:

def question():
    ask = input("Are you OK?:").lower()
    if ask != 'yes':
        question()
    else:
        return ask


print(question())

But in this code it works only if I answer 'yes' straight away, if I answer first time 'no' it ask again as expected and when second time I answer 'yes' it returns and prints: NONE.

2
  • if ask != 'yes' then the function will just call itself indefinitely (or until max recursion depth is exceeded). Commented Dec 11, 2020 at 23:35
  • I see it now :-) However when I put question inside the def question() and do print(question()) something strange is coming, when I type in in answer Yes it works but when 'No' it asks again and when I answer 'yes' returns NONE. Commented Dec 11, 2020 at 23:46

1 Answer 1

0

question() is asking a new question in each call. print(question()) just concern the answer from the first question. When you type No for your first question, question() is called asking the second question, and return None to your first question. Any answers after that just ask new question if ask != yes or return result to that question if ask == yes but do not affect the None return in first question.

Instead of keep asking new question, you can use while loop to keep asking new answer for the same question until the condition is met:

def question():
    ask = input("Are you OK?:").lower()
    while ask != 'yes':
        ask = input("Are you OK?:").lower()
    return ask

print(question())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.