I have a functions in Python which has a series of if statements.
def some_func():
if condition_1:
return result_1
if condition_2:
return result_2
... #other if statements
But I want that the order of these if statements is changed every time I call the function.
Like if I call the function there can be a case when condition_1
and condition_2
both are true but since condition_1
is checked first thus I will get result_1
but I want that when I call the function second time some other random condition to be checked. (since I have only five if statements in the function therefore any one of the five conditions).
So is there any way to do this like storing the conditions in a list or something.
Any help will be appreciated.
The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).
The shuffle() method randomizes the items of a list in place.
You can use random. shuffle() method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list.
You can create list of condition
and result
then shuffle
them like below:
import random
def some_func(x):
lst_condition_result = [((x>1), True), ((x>2), False)]
random.shuffle(lst_condition_result)
for condition, result in lst_condition_result:
if condition:
return result
Output:
>>> some_func(20)
True
>>> some_func(20)
False
>>> some_func(20)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With