-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
  • 55,782
  • 14
  • 81
  • 108

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,427
  • 5
  • 44
  • 81
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
  • 37,849
  • 12
  • 53
  • 71