0

How to call a function depending on the user input?

Hi team I am trying to get a user input and then store it in a list now what I want to do is, call a specific function depending on the [i] th value in that list for example my_list[0] has value 'a' then I want to call the function_a() #which i have already defined my_list[1] has value 'b' stored at that index then i want to call function_b #again function_b has already beem defined so basically, I want to see if the value in that list matches any of my function then I want to trigger that function example in detail: user_input : 'text' list = [] for i in user_input: list.append[i] so my list becomes ['t','e','x','t'] now, I have specific functions for each of these alphabets (i think i should have a dictionary or something where keys are alphabets and values are respective function, I don't know if thats even phaaaasssibbble) but i want to call those function as per these values in the list so here i want my program to call function_t function_e function_x function_t

28th Sep 2018, 7:07 PM
Zubair Khan
Zubair Khan - avatar
9 Answers
28th Sep 2018, 7:10 PM
Zubair Khan
Zubair Khan - avatar
+ 5
leave the parantheses in your dictionary
29th Sep 2018, 4:04 AM
Oma Falk
Oma Falk - avatar
+ 2
yes, you can declare all functions in a dictionary: dict = {"a": func_a, "b": func_b, "c": func_c, .....} this gets you the input as list: list = list(input("Enter something:")) now you only need to iterate over the list and call the corresponding functions: for x in list: dict[x]
28th Sep 2018, 7:24 PM
Kevin Dietrichstein
Kevin Dietrichstein - avatar
+ 1
sorry, I was creating the dictionary before the function, when i put that line after my function the error is gone now let me see how to iterate through this dictionary
28th Sep 2018, 7:35 PM
Zubair Khan
Zubair Khan - avatar
+ 1
Looks like your problem has been solved. Great!
28th Sep 2018, 8:51 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
Yes, what Oma said. Using parentheses means you are actually calling the function.
29th Sep 2018, 4:24 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
ok understood, thanks
29th Sep 2018, 6:51 AM
Zubair Khan
Zubair Khan - avatar
0
Kevin Dietrichstein I tried creating a dictionary but it says 'undefined name 'function_a' # my function name is function_a()
28th Sep 2018, 7:31 PM
Zubair Khan
Zubair Khan - avatar
0
Kishalaya Saha Actually there is a new problem my dictionary is dict = {"a": function_a(), "b": function_b...... and so on} but when I am running a program all these functions are getting executed 😅
28th Sep 2018, 9:08 PM
Zubair Khan
Zubair Khan - avatar