程序不会循环

时间:2018-05-07 19:40:36

标签: python

def main():
        ToDo = []
        ToDo.append("shower")
        ToDo.append("make breakfast")
        ToDo.append("do homework")
        ToDo.append("walk dog") 
        ToDo.append("eat dinner") 
        ToDo.append("sleep") 

        running = True
        ToDo = []
        ToDo.append("shower")
        ToDo.append("make breakfast")
        ToDo.append("do homework")
        ToDo.append("walk dog") 
        ToDo.append("eat dinner") 
        ToDo.append("sleep") 

        running = True

        while(running):
            print("\n1. add an element") 
            print("2. delete an element")
            print("3. edit an element")
            print("4. print an element")
            print("5. exit")    
            choice = int(input("Please enter 1-5: "))
            if choice == 1:
                ToDo.append(input("Enter an element: "))
            elif choice == 2:
                pos = int(input("Please enter the index of the element to delete (0-"+ str(len(ToDo) - 1)+"): "))
                if pos >=0 and pos < len(ToDo):
                    ToDo.pop(pos)
                else:
                    print("Wrong index: " + pos)     
            elif choice == 3:
                pos = int(input("Please enter the index of the element to delete (0-"+ str(len(ToDo) - 1)+"): "))
                if pos >=0 and pos < len(ToDo):
                    ToDo[pos] = input("Enter an element: ")
                else:
                    print("Wrong index: " + pos)  

            elif choice == 4:
                pos = int(input("Please enter the index of the element to delete (0-"+ str(len(ToDo) - 1)+"): "))
                if pos >=0 and pos < len(ToDo):
                    print(ToDo[pos])
                else:
                    print("Wrong index: " + pos)
            elif choice == 5:
                print("Exiting...")
                restart = input("Do you want to start again").lower()
                if restart == "yes":
                    main()
                else:
                    exit()  
            else:
                print("Please enter a valid option")

我的程序以我想要的方式工作,但是在添加以下代码以循环整个程序之后,它根本不运行程序。它应该运行,如果用户输入5,程序应该询问他们是否想重新开始。如果他们说是,那么它将进入main,否则它将结束该程序:

    restart = input("Do you want to start again").lower()           
    if restart == "yes":
        main()
    else:
        exit()

1 个答案:

答案 0 :(得分:1)

您的脚本在退出提示中递归调用main,您可能不想这样做。

无关:为什么要复制init例程?

你可能意味着这个:

restart = input("Do you want to start again").lower()           
if restart != "yes":
    exit()
else:
    # re-init
    ToDo = []
    ToDo.append("shower")
    ToDo.append("make breakfast")
    ToDo.append("do homework")
    ToDo.append("walk dog") 
    ToDo.append("eat dinner") 
    ToDo.append("sleep") 

如果用户为重新启动键入yes,它将循环回到主循环的开头。