suppose i have 10 different functions.

i generate a random no. between 1 to 10.
depending on its value i want to call the fucntion.
eg. no. 3 call func, no. 8 calls func 8... etc.
how do i do it using a loop without using the if else statement as it makes the code too long.

suppose i have 10 different functions.

i generate a random no. between 1 to 10.
depending on its value i want to call the fucntion.
eg. no. 3 call func, no. 8 calls func 8... etc.
how do i do it using a loop without using the if else statement as it makes the code too long.

A dictionary. The key is the number, the value is the function.

Generate random number, then do something like my_function_dict[my_random_number]() . Get it?

EDIT: To illustrate:

>>> def funcA():
...     print 'A'
...     
>>> def funcB():
...     print 'B'
...     
>>> def funcC():
...     print 'C'
...     
>>> func_dict = {1:funcA, 2:funcB, 3:funcC}
>>> random_number = 2
>>> func_dict[random_number]()
B
>>>

You can make a list with your functions

import random
funcs = [func0, func1,func2,func3,func4,func5,func6,func7,func8,func9,]
funcs[random.randrange(10)]() # <- call a random function
random.choice(funcs)() # <- another way

edit: jlm699 was faster :)

i did it with the help of a dictionary.

thanks for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.