1

I am wondering how to run functions from a list, and calling them using the random module, but I can't seem to get it to work can anyone help? Here is an example below.

import random
def word1():
       print "Hello"
def word2():
       print "Hello again"

wordFunctList = [word1, word2]

def run():
       printWord = random.randint(1, len(wordFunctList))-1
       wordFunctList[printWord]
       run()
run()

So I wanted to do this in an infinite loop, but all I get for output is

Hello
Hello again

Then the program just doesn't do anything else? Can anyone help me? Btw, I am using the app pythonista. Also I am a programming NOOB. I just recently started with python.

The whole reason I am asking this question is because I am making a text based world generator, and I want to define functions for biomes, then randomly call them from a list while the world is generating.

1 Answers1

3

I'd do it this way:

import random

def word1():
    print "Hello"

def word2():
    print "Hello again"

wordFunctList = [word1,  word2]

def run():
    # Infinite loop, instead of recursion
    while True:
        # Choose the function randomly from the list and call it
        random.choice(wordFunctList)()

run()

Read this answer. It explains why you should avoid tail recursion and use infinite loop instead.

Explanation on random.choice(wordFunctList)():

wordFunctList is a list with function objects:

>>> print wordFunctList
[<function word1 at 0x7fcb1f453c08>, <function word2 at 0x7fcb1f453c80>]

random.choice(wordFunctList) chooses the function and returns it:

>>> random.choice(wordFunctList)
<function word2 at 0x7f9ce040dc80>

random.choice(wordFunctList)() calls the returned function:

>>> print random.choice(wordFunctList)()
Hello again # Outputs during the function call
None        # Returned value

With extra parentheses (random.choice(wordFunctList)()()), you were calling the returned value of the function, that is None, but None is not callable and that's why you were getting the error.

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143