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
>>>

Edited 7 Years Ago by jlm699: n/a

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 :)

Edited 7 Years Ago by Gribouillis: n/a

This question has already been answered. Start a new discussion instead.