【问题标题】:Resetting ALL variables when running main() in a loop在循环中运行 main() 时重置所有变量
【发布时间】:2018-06-18 19:36:34
【问题描述】:

当我询问用户:“你想再次运行该程序”时,我希望再次运行一个程序。不会退出,是的循环并再次运行 main。但是我注意到 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()

【问题讨论】:

  • 不使用全局变量?存储了哪些“旧变量赋值”?
  • 是的。所有变量都应该是本地的,控制main()是否再次运行的逻辑应该在main()之外。
  • 我搞定了。只是一个快速的问题。如果我在 main() 中调用 main(),是保留之前迭代中已经定义的所有变量,还是重置它?
  • 调用一个函数会创建一个新的栈帧,所以所有的局部变量都未初始化。全局变量不会重置。
  • 对于未初始化的变量是否有本地工作的最佳实践?在再次调用 main() 之前,是否只需将所有变量设置为 =None?这样做会清除堆栈吗?谢谢@kindall

标签: python variables memory


【解决方案1】:

您可以做的一件事是本地化变量并使用清理功能来处理启动新会话。

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 清除它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2013-06-20
    • 2014-05-14
    • 2017-09-07
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多