Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you shuffle functions using python to then call the shuffled result?

I am trying to make functions which would print separate questions. I then want the functions to be put into a list and shuffled with the shuffled functions being called in their shuffled order.

I tried to change the functions into variables and then put the variables in a list. I then tried to use random.shuffle()
to then shuffle the list and then print the shuffled list by using return(questionlist[0]). However, it simply returned an error message.

My code looked a little like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import random
def Question1():  
    print("Which one of these is a safe password?")

def Question2():   
    print("What can you do to get less spam?")

def Question3():   
    print("What term describes the act of annoying someone online?")
def questionfunction():
    q1 = Question1
    q2 = Question2
    q3 = Question3
    questionlist = [q1,q2,q3]
    random.shuffle(questionlist)
    return(questionlist[0])
    return(questionlist[1])
    return(questionlist[2])
questionfunction()

>Solution :

You have to actually call the functions. Further, you don’t want to return until you actually call all three. You also don’t need any additional variables; Question1 is already a variable that refers to the function originally bound to it.

def questionfunction():
    questionlist = [Question1, Question2, Question3]
    random.shuffle(questionlist)
    questionlist[0]()
    questionlist[1]()
    questionlist[2]()

You could, alternatively, just return the shuffled list and let the caller call the functions.

def questionfunction():
    questionlist = [Question1, Question2, Question3]
    random.shuffle(questionlist)
    return questionlist

for q in questionfunction():
    q()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading