Search code examples
pythonmenu

Returning back to main menu in python


I have a printout of my coding below, where I have a menu, where a user will select an option, directing them into a certain activity (A, B, C, D, X), which has more substance than I have posted, but I didn't want to submit an even bigger wall of text code.

def printMenu ():
    print("Playing Statistics Calculator")
    print("A: Positions in Basketball and relevent Key Performance Indicators")
    print("B: Calculate your per-game statistics")
    print("C: Compare your statistics to other players in your position")
    print("X: Exit")

def main():
    choice = printMenu()
    choice

main()

selection = input("Please choose a selection: ")

if selection == "A":
    print("You are interested in looking at the Key Performance Indicators (KPIs) that we think are important for each position. Please select a position below:")
    main()
    selection
elif selection == "B":
    print("Now you know the important KPIs related to each position, which position are you interested in, in our team?")
    main()
    selection
elif selection == "D":
    print("comparison calculations in here")
    main()
    selection
elif selection == "X":
    exit()
else:
    print("Try again, please ensure the letters are in capitals and are shown in menu")
    main()
    selection

My problem is that when I try to take the user back to main menu at the end of the activity, it prints the menu as intended, but does not allow the user to input a selection, and if it does allows for it, it just stops the program, rather than looping back and running it again properly.

I am very new to coding in Python, but have a year or so experience in R if that helps.


Solution

  • Try the following structure

    def printMenu():
        print("Playing Statistics Calculator")
        print("A: Positions in Basketball and relevent Key Performance Indicators")
        print("B: Calculate your per-game statistics")
        print("C: Compare your statistics to other players in your position")
        print("X: Exit")
        return input("Please choose a selection: ").upper()
    
    def program(selection):
        if selection == "A":
            print("You are interested in looking at the Key Performance Indicators (KPIs) that we think are important for each position. Please select a position below:")
        elif selection == "B":
            print("Now you know the important KPIs related to each position, which position are you interested in, in our team?")
        elif selection == "C":
            print("comparison calculations in here")
        else:
            print("Try again, please ensure the letter is shown in the menu.")
    
    selection = printMenu()
    while selection != 'X':
        program(selection)
        print()
        selection = printMenu()