-1

I want to build an options menu where the user types a number and according to the number he calls a function that does something .. For example:

def func1():
    pass
def func2():
    pass
def func3():
    pass

user_input = int(input("enter option: "))
if user_input == 1:
    func1()
elif user_input == 2:
    func2()
elif user_input == 3:
    func3()

So instead, build something in a few lines of code that will work in the same way and of course also on a function that gets parameters

khelwood
  • 52,115
  • 13
  • 74
  • 94

2 Answers2

1

You can store the functions themselves in a dictionary and then access them using the user input

def func1():
    pass
def func2():
    pass
def func3():
    pass

funcs = {1:func1, 2:func2, 3:func2}

user_input = int(input("enter option: "))
funcs[user_input]()
C_Z_
  • 7,136
  • 5
  • 37
  • 73
0

You can have a dict which can fetch the right function for you to execute:

def func1():
    pass
def func2():
    pass
def func3():
    pass

f = {1:func1, 2:func2, 3: func3}

user_input = int(input("enter option: "))
if user_input in f:
    f[user_input]()
quamrana
  • 33,740
  • 12
  • 54
  • 68