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

Time:11-30

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:

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()

CodePudding user response:

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()
  • Related