[Python] match/case statement in python does not allow use of list item as the case [duplicate]

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I have an os dependent program and I wanted to use a match/case statement and function to match a key input to its corresponding value. I have the "values" for each os stored in different tuples and I was hoping to use these as the cases by doing something like this (but in a class):

    import os
    import CONTROLS # File with ASCII values

    # UP DOWN RIGHT LEFT
    if os.name == "posix":
    CONTROL_CODES = range(65, 69)
    else:
    CONTROL_CODES = (72, 80, 77, 75)

    pressed = None
    def _input_control_codes(char):
    global pressed
    match char:
    case CONTROL_CODES[0]: # UP
    pressed = CONTROLS.UP
    return
    case CONTROL_CODES[1]: # DOWN
    pressed = CONTROLS.DOWN
    return
    case CONTROL_CODES[2]: # RIGHT
    pressed = CONTROLS.RIGHT
    return
    case CONTROL_CODES[3]: # LEFT
    pressed = CONTROLS.LEFT
    return

    _input_control_codes(65) # example
    print(pressed)


    The above yields the error message:

    File "~/main.py", line 14
    case CONTROL_CODES[0]: # UP
    ^
    SyntaxError: invalid syntax



    I was wondering if there was a way to accomplish this without having to use an if statement or manually writing 2 match/case statements?

    Continue reading...

Compartilhe esta Página