debugging 为什么当用户首先触发else语句然后回答yes时,这个repeat循环没有按预期工作?

sauutmhj  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(108)
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()
q8l4jmvw

q8l4jmvw1#

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 :)

相关问题