pythonperformancereorganize

How can I organize my code so that it's neater?


from subprocess import call
command = input(': ')
if command == '1':
    call('notepad.exe')
elif command == '2':
    call('calc.exe')
else:
    print('command not found')

I have similar code except it's a lot more if statements. Main objective here is to make it take up less space / make it more organized. I am unsure of how to proceed with such task.


Solution

  • You can e.g. create a dictionary of commands:

    menu = {'1': 'notepad.exe', '2': 'calc.exe'}
    

    Then you can use:

    command = input(': ')
    if command in menu:
        call(menu[command])
    else:
        print('command not found')