function - Python doubts about calling func and Syntax -


i'm totally newbie, i'm still reading python docs myself syntax doubts.

i have functions in my.py

def f1:   pass  def f2:   pass  def f3:   pass 

so choose number call function like:

a = input('insert function number')  

"f$d"() %a #i tried that, totally weird, i'm newbie (a kinda stupid).

sorry if it's stupid question, don't have idea how can make it.

you can achieve quite easily. make list of functions:

list_func = [f1, f2, f3] 

and th execution:

a = int(input('insert function number: ') #get input , convert integer list_func[a]() #execute function inputted 

or without list_func:

inp = int(input('insert function number: ') #get input , convert integer eval('f%d'%inp)  

keep in mind, not use eval() often. it's bit insecure.

alternatively, can call globals(), it's able return dictionary of global variables , functions:

globals()['f%d'%inp]() 

nah, that's it. hope helps!


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -