pythonpython-3.xlist

How to create simple menu in Python with list functions?


Please have a look at the exercise that i was asked to do. I am struggling for hours now to make it work.

There has to be a menu with the following choices: add a number, remove number (enter placeholder), show list. Each time choice is made program should ask if we want to re-run the script.

Tried loops, functions and it just doesn't seem to work with me.

See the code below.

Thank you in advance!

def list():

    operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list

''')
    mylist = []

    if operation == '1':
        print("Type the number you would like to add to the list: ")
        number = int(input())
        mylist.append(number)

    elif operation == '2':
        print("Type position of the element number you like to remove from the list: ")
        number = int(input())
        mylist.pop(number)

    elif operation == '3':
        print(mylist)

    else:
        print('You have not chosen a valid operator, please run the program again.')

    again()

def again():
    list_again = input('''
Would you like to see main menu again? (Y/N)
''')

    if list_again.upper() == 'Y':
        list()
    elif list_again.upper() == 'N':
        print('OK. Bye bye. :)')
    else:
        again()

list()

Solution

  • Verified Code

    mylist = []
    def list():
    
        operation = input('''Select operation:\n [1] Add number to the list \n [2] Remove number from the list \n [3] Display list\n ''')
    
    
        if operation == '1':
            print("Type the number you would like to add to the list: ")
            number = int(input())
            mylist.append(number)
    
        elif operation == '2':
            print("Type position of the element number you like to remove from the list: ")
            number = int(input())
            mylist.pop(number)
    
        elif operation == '3':
            print(mylist)
    
        else:
            print('You have not chosen a valid operator, please run the program again.')
    
        again()
    
    def again():
        list_again = input('''Would you like to see main menu again? (Y/N)''')
    
        if list_again.upper() == 'Y':
            list()
        elif list_again.upper() == 'N':
            print('OK. Bye bye. :)')
        else:
            again()
    
    list()
    

    Cheers!