Reputation: 3535
I am making a project that involves calling functions from a list, but I can't get it to work straight. There is some problem with calling the functions from the list, and I just can't seem to figure out why. I have some code below for an example, and the output will be provided as well. The code provided is just an example of the basic idea of what I am trying to do. It is not my actual code. Don't worry though, it is the basic idea.
import random, time
def word1():
print "Hello"
def word2():
print "Goodbye"
words = [word1(), word2()]
def run():
while True:
random.choice(words)()
time.sleep(0.5)
run()
And the output I get is this:
TypeError: 'NoneType' object is not callable
For all I know, this could be some simple error that I am overlooking, but for the life of me, can not figure out. Help!
Upvotes: 1
Views: 65
Reputation: 309929
You're storing the function results in the list1, not the functions themselves.
i.e. change:
words = [word1(), word2()]
to:
words = [word1, word2]
1And the results are all None
which is why you get the NoneType
not callable error...
Upvotes: 2
Reputation: 57480
"word1()
" is not the function word1
; it is instead the return value from calling word1()
, which, because word1
doesn't explicitly return anything, is None
. What's word1
? It's just word1
. Thus, the declaration of words
should be changed from:
words = [word1(), word2()]
to:
words = [word1, word2]
Upvotes: 3
Reputation: 77107
You call the functions already within the list. You want to defer.
words = [word1, word2]
def run():
while True:
random.choice(words)()
time.sleep(0.5)
Upvotes: 1