# How do I randomly call one of three functions without using an if statement? [duplicate]

170
April 17, 2018, at 03:52 AM

• Choosing a function randomly 5 answers

I created a class "Bruch" that creates two fractions from random numbers in a given range. There are three different types of operations that are defined in three different functions, for addition (bruchplus), subtraction(bruchminus) and multiplication (bruchmulti).

The "select(self)" function randomly calls one of these.

The code works totally fine, but I am not happy with the "if" clause in select(self). It's clumsy and ugly. There must be a more pythonic way to accomplish this. (I tried to call the functions from within a list, but that will call all the three functions, even if i just return e.g. list). Looking forward to your input!

``````class Bruch:
def __init__(self, name):
self.name = 'BRUCHRECHNEN'
print(self.name)
print('')
self.a = Fraction(rdm.randrange(1,10,2),rdm.randrange(2,10,2))
self.b = Fraction(rdm.randrange(1,10,2),rdm.randrange(2,10,2))
#randomly selects + / - / x and calls the respective function
def select(self):
number = rdm.randint(0,2)
if number == 0:
p = self.bruchplus()
elif number == 1:
p = self.bruchminus()
else:
p = self.bruchmulti()
return p
``````

Perhaps you could use `random.choice()` like this:

``````fn = random.choice([self.bruchplus, self.bruchminus, self.bruchmulti])
p = fn()
``````
POPULAR ONLINE

#### Why is my interval returning different results based on pushing to an array? ### Error appears when attempting to create a map with folium in Python

My assignment is to create an html file of a mapThe data has already been given to us

251 ### Iterate through subnet and run portscan function

I'm trying to write a python program that will ping sweep a given network (192168

185 ### Python : Getting Key error print (cpr) KeyError: 4 [on hold]

My csv file is:

241 ### simple method inheritance in python 3

Newbie python inheritance questionwhen you write the following:

165