Calling functions in module by choice in main python program

Question:

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
Asked By: Looky Funny

||

Answers:

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()
Answered By: StonedTensor
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.