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()
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 :
None
False
True
... 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.
repeat()
def repeat(): r = True while r: ques = input(...).lower() if ques == "no": r = False
which avoids useless recursion issues.Have a nice day :)
1条答案
按热度按时间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':
see https://realpython.com/python-return-statement/ .
And in a whileloop
None
is considered asFalse
as it is notTrue
.So when your function ends here after the execution of repeat :
the function returns
None
value instead ofTrue
, and therefore the while loop ends.You should instead use :
which will return what
repeat()
returns (True in case of the following answer "yes").However I would have not done the program like this.
which avoids useless recursion issues.
Have a nice day :)