在循环中运行main()时重置所有变量

2024-06-23 02:48:29 发布

您现在位置:Python中文网/ 问答频道 /正文

当我询问用户:“Doyouwanttoruntheprogrammearth”时,我希望再次运行一个程序。不去退出,是的循环和运行主要再次。但是我注意到python保存了旧的变量赋值。有没有一种快速的方法来清除内存,以便在程序循环时再次存储新的变量?你知道吗

现在我得到的是:请关闭程序并重新打开它!想让它更优雅:

到目前为止我得到的是:

def main()
    print("Do you want to solve another problem?")
    answer = input()
    while answer not in["yes","no"]:
        answer = input()

    if answer == "yes":
        print("Please close the program and rerun it")
        #main() #<-this is not working as expected
    else:
        exit()

Tags: 方法内存用户answer程序inputmaindef
1条回答
网友
1楼 · 发布于 2024-06-23 02:48:29

您可以做的一件事是本地化变量并使用clean-up函数来处理启动新会话

def main()
    print("Do you want to solve another problem?")
    answer = input()
    while answer not in["yes","no"]:
        answer = input()

    if answer == "yes":
        answer = None
        print("Please close the program and rerun it")
        #main() #<-this is not working as expected
    else:
        exit()

区别在于if answer == 'yes'将设置answer = None以清除它

相关问题 更多 >