5

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?

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

@RonE These are not function pointers. functionA is a reference to a function object. And the difference matters if you want an actual explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.