79505484

Date: 2025-03-13 05:32:49
Score: 0.5
Natty:
Report link

This menu-maker came from following a discussion about how to force a response to an input statement. It is the only code I have ever written that I thought might be of use to others. Years too late to help Milan :(

def make_menu(alist, columns=3, prompt='Choose an item > '):

    # adds an item number to each element of [alist] ([menu_items]).
    # pop and concatenate [menu_items] elements
    # according to number of columns,
    # and append to [menu].
    # join [menu] elements to form input prompt


    alist.append('Quit')
    menu_items = [f'[{i}] {j}' for i, j in enumerate(alist, 1)]
    choices = [str(i + 1) for i in range(len(alist))]
    menu_row = ''
    count = 0
    menu_items.reverse()
    col_width = len(max(menu_items, key = len))
    menu =[]
    # build the final menu until no more menu_items
    while menu_items:
        count += 1
        menu_row = menu_row + menu_items.pop().ljust(col_width + 3)
        if count == columns or not menu_items:
            menu.append(menu_row)
            count = 0
            menu_row = ''

    menu.append(f'\n{prompt}')
    mn = 1
    mx = len(alist)
    while True:
        choice = input('\n'.join(menu))
        if choice in choices:
            break
        else:
            print(f'Enter a number between {mn} and {mx}\n')
    ch = int(choice)

    if ch == len(alist):
        print("\n\nQuit")
        exit()
    return choice, alist[ch - 1]

if __name__ == "__main__":
    mylist = 'cat dog monkey turkey ocelot bigfoot drop-bear triantewontegongalope'.split()
    mychoice,  item = make_menu(mylist, columns=3)
    print(f'\nYou chose item [{mychoice}] \nwhich was {item}')
Reasons:
  • Blacklisted phrase (1): :(
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: ceilingcat