Matt
Matt

Reputation: 395

How to Run a Random Function in Python 2

Suppose I have two functions:

functionA() and functionB()

I do not care which function runs, but I do want just ONE of them to run randomly--ie, if I run the script a hundred times, both should be played near 50 times.

How can I program that into Python 2?

Upvotes: 5

Views: 423

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52223

In Python, functions are first class citizens so you can put them in a list and then randomly select one of them at every turn using random.choice:

>>> import random

>>> functions = [functionA, functionB]
>>> for _ in range(100):
...     function = random.choice(functions)
...     function()

Upvotes: 3

Related Questions