简体   繁体   中英

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.

You can eg 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM