pythonstack

Calling a function from a list makes the list go empty


I am making a program as a school project that I want to make it feel like a webpage by allowing the user to enter a specific number in any page that makes it go back a page.

I implemented it using a stack (I'm not exactly sure if it matters but I did not set a max limit of elements for it since it didn't make sense to set one). Here's a small part of my code where I want to focus:

currentPage=[] #page stack

def goTo(page):
    currentPage.append(page)

def goBack(): #redundant for now
    global currentPage
    print(currentPage)
    del currentPage[-1]

def mainMenu():
    print("1. Order item\n2. Admin login\n3. Quit\n")
    global currentPage
    print(currentPage) #14
    choice=int(input("Please enter your choice: "))
    if choice==1:
        goTo(order())
    elif choice==2:
        goTo(adminMenu())
    elif choice==3:
        goBack()

goTo(mainMenu())
while True:
    if len(currentPage)==0:
        print("Thank you for using our program! <3")
        break
    currentPage[-1]()

[edited]: I expect the print in line 14 to print [mainMenu()] but it prints [] instead.

it seems like calling a function from a list makes the list become empty for some reason. Could you suggest any workarounds for this?


Solution

  • To address the issue, avoid executing the functions when adding them to the currentPage list. Instead of goTo(mainMenu()), use goTo(mainMenu) to store the function itself. This prevents the list from becoming empty due to function execution.

    By storing the functions without executing them in the goTo function, you can maintain the functionality without encountering the issue of an empty list.