Friday 15 June 2012

python - Execute a function randomly -



python - Execute a function randomly -

consider next functions:

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

is there way pick function run randomly? tried using:

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

but returns both functions, want homecoming 1 function.

only phone call selected function, not both of them:

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

below demonstration:

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

your old code called both functions when list [a(),b()] created, causing python print both a , b. afterwards, told random.choice take list [none, none]1, nothing. can see demonstration below:

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

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

>>> random.choice([a,b]) <function b @ 0x01afd970> >>> random.choice([a,b]) <function @ 0x01afd930> >>>

it calls function.

1functions homecoming none default. since a , b lack return-statements, each homecoming none.

python function random

No comments:

Post a Comment