1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Is there a better way to map a user input to a list of possible replies than this...

Discussão em 'Python' iniciado por Stack, Novembro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have this function I came up with as a python noob that takes an "inputMap", a 2-dimensonal array as follows:

    exampleInputMap = [
    ['1', 'a', -1], # do the first action
    ['2', 'b'], # do the second action
    ['3', 'h'], # print help
    ['4', 'q'] # quit the program
    ]

    def mapInputToAction(inputMap, matchFirstCharOnly=True, prompt='> '):
    while True:
    response = input(prompt)
    if len(response) == 0:
    for index, row in enumerate(inputMap):
    if -1 in row:
    return index
    else:
    for index, row in enumerate(inputMap):
    if matchFirstCharOnly:
    if response[0] in row:
    return index
    else:
    if response in row:
    return index


    This is used in a while loop, fed into a match/case statement. It gets an input from the user each time, and then returns an integer that tells the match/case what action to do each time. Is this a good way to accomplish this, or is there a better way to do this (perhaps with dictionaries)? I'm trying to build good coding habits by practicing, but I don't want practice bad techniques.

    Continue reading...

Compartilhe esta Página