Home > Net >  Calling functions in module by choice in main python program
Calling functions in module by choice in main python program

Time:11-12

Can I call function from module in the main python file by user choice?

something like this:

module file

def product_1(a,b):
    return a*b

def sum_1(a,b)
    return a b

main file

Can I call function in the main file with list by user choice from input?

a=input()
b=input()
list1=['product_1','sum_1']
x=input('Enter choice')
list1[x]

This results in the following error:

TypeError: 'list' object is not callable

CodePudding user response:

It's possible to have functions in a list/dictionary that you can call. For your case, it sounds like you need a dictionary to determine the proper function.

Your main.py should look like...

from module import product_1, sum_1
def main():
    a=input()
    b=input()
    function_mapping={'product_1':product_1, 'sum_1':sum_1 }
    x=input('Enter choice')
    print(function_mapping[x](a,b))
main()
  • Related