Search code examples
python-3.xloopsdebuggingrepeat

Why doesent this repeat loop work as intended when the user first triggers the else statement and then answers yes?


def repeat():
    ques = input("Would you like to repeat the program? (yes or no): ").lower()

    if ques == "yes":
        return True

    elif ques == "no":
        exit()

    else:
        repeat()


bool = True
while bool:
    bool = repeat()

Solution

  • Okay so... The first thing you've done wrong is to use recursion to repeat the program: https://en.wikipedia.org/wiki/Recursion.

    By default in python, a function returns 'None':

    >>> def f():
    ...     x = 0
    ... 
    >>> print(f())
    None
    

    see https://realpython.com/python-return-statement/.

    And in a whileloop None is considered as False as it is not True.

    So when your function ends here after the execution of repeat :

    ...
        else:
            repeat()
    

    the function returns None value instead of True, and therefore the while loop ends.

    You should instead use :

    ...
    else:
        return repeat()
    

    which will return what repeat() returns (True in case of the following answer "yes").

    However I would have not done the program like this.

    def repeat():
        r = True
        while r:
           ques = input(...).lower()
           if ques == "no":
               r = False
    

    which avoids useless recursion issues.

    Have a nice day :)