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()
uj5u.com熱心網友回復:
好吧...你做錯的第一件事是使用遞回來重復程式: https ://en.wikipedia.org/wiki/Recursion 。
默認情況下,在 python 中,函式回傳“None”:
>>> def f():
... x = 0
...
>>> print(f())
None
請參閱https://realpython.com/python-return-statement/。
并且在 whileloopNone中被認為False不是True。
因此,當您的函式在執行repeat后在這里結束時:
...
else:
repeat()
該函式回傳Nonevalue 而不是True,因此 while 回圈結束。
您應該改用:
...
else:
return repeat()
這將回傳回傳的內容repeat()(在以下答案“是”的情況下為真)。
但是我不會做這樣的程式。
def repeat():
r = True
while r:
ques = input(...).lower()
if ques == "no":
r = False
這避免了無用的遞回問題。
祝你今天過得愉快 :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504637.html
標籤:python-3.x 循环 调试 重复
上一篇:C中的反向行函式無法預測
