Randomly execute a function

Consider the following functions:

def a(): print "a" def b(): print "b" 

Is there a way to select a function to run randomly? I tried using:

 random.choice([a(),b()]) 

but it returns both functions, I just want it to return one function.

+5
source share
2 answers

Call only the selected function, not both of them:

 random.choice([a,b])() 

Below is a demo:

 >>> import random >>> def a(): ... print "a" ... >>> def b(): ... print "b" ... >>> random.choice([a,b])() a >>> random.choice([a,b])() b >>> 

Your old code called both functions when the list [a(),b()] , causing Python to print both a and b . Then he told random.choice to select from the list [None, None] 1 which does nothing. This can be seen in the demo below:

 >>> [a(),b()] a b [None, None] >>> 

However, the new code uses random.choice to randomly select a function object from the list [a,b] :

 >>> random.choice([a,b]) <function b at 0x01AFD970> >>> random.choice([a,b]) <function a at 0x01AFD930> >>> 

Then it calls only this function.


1 By default, functions return None . Since a and b missing return-statements, each returns None .

+14
source

Is this what you want?

random.choice([a,b])()

0
source

Source: https://habr.com/ru/post/1205811/


All Articles