From this thread: How do I perform a random event in Python by picking a random variable?
I learned that it's possible to put some functions into a list, and by using random.choice()
, call one of them to generate a random event.
I'm interested in doing this because I'm writing a fairly small text based game as part of a beginner's tutorial.
But when I write what I think will give me the desired result(that is, just one of the functions being called and printing its string:
import random def func_test_1(): print "This is func_test_1." def func_test_2(): print "This is func_test_2." def func_test_3(): print "This is func_test_3." my_list = [func_test_1(), func_test_2(), func_test_3()] random.choice(my_list)
I get this result:
C:\Windows\system32\cmd.exe /c python random_func.py This is func_test_1. This is func_test_2. This is func_test_3. Hit any key to close this window...
Which is all three functions being called and printing.
Could someone help me out with the correct syntax to do this? Thank you.
To select a random element from a list in python, we can use the choice() function defined in the random module. The choice() function takes a list as input and returns a random element from the list every time it is executed.
Random integer values can be generated with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].
You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers. To create a list of unique random numbers, we need to use the sample() method.
With the parentheses you call the function. What you want is assigning them to the list and call the choice later:
my_list = [func_test_1, func_test_2, func_test_3] random.choice(my_list)()
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