P
P
piffo2020-08-31 02:20:42
Python
piffo, 2020-08-31 02:20:42

How can python code be shortened?

def command_check():
    global is_on

    if command == "view":
        view()
        is_on = False
    elif command == "viewAll":
        viewAll()
        is_on = False
    elif command == "num":
        num()
        is_on = False
    elif command == "add":
        add()
        is_on = False
    elif command == "change":
        change()
        is_on = False
    elif command == "del":
        delet()
        is_on = False
    elif command == "search":
        search()
        is_on = False
    elif command == "exit":
        exit()
    else:
        print("Ошибка. Несуществующая команда.")

How can this code be shortened?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramis, 2020-08-31
@ramzis

Can you do it like this

def view():
    pass
def viewAll():
    pass
def num():
    pass

def command_check(command):
    com = {'view':view,'viewAll':viewAll,'num':num}
    try:
        com[command]()
    except:
        print("Ошибка. Несуществующая команда.")
    
command_check('view')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question