Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle the order of if statements in a function in Python?

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.

like image 851
Michael Stevens Avatar asked Oct 10 '21 14:10

Michael Stevens


People also ask

How do you shuffle a sequence in Python?

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.

Which function is used to shuffle in Python?

shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).

How can you randomize the items of a list in place in Python?

The shuffle() method randomizes the items of a list in place.

How do you shuffle images in a folder in Python?

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.


1 Answers

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
like image 86
I'mahdi Avatar answered Nov 15 '22 00:11

I'mahdi