user233699
user233699

Reputation: 31

How to add a function to a list

I tried searching for answers but couldn't find it.

I'm trying to add some functions that have been defined to a list and then later get the list to spit out the function. Ultimately, I want the list to be able to randomly assign which function to run. But for now, I just want to know how to add the function.

Here's what I have so far.

#!/usr/bin/python

def question_1():
    print "This is question 1"
    print "Please in put your answer for question 1"
    raw_input()
    print "Thanks"

def question_2():
    print "This is question 2"
    print "Please in put your answer for question 2"
    raw_input()
    print "Thanks"


tier_1_questions = [question_1(), question_2()]
print tier_1_questions[0]

For starters, I'm just trying to print question 1, but it's still printing out both questions. Even if I remove the last line of code, it is still printing out which is weird.. I would really appreciate help on this. Thanks!

Upvotes: 0

Views: 844

Answers (3)

OAnt
OAnt

Reputation: 131

You should write :

tier_1_questions = [question_1, question_2]

instead of

tier_1_questions = [question_1(), question_2()]

question_1() means you are executing the function therefore what is stored in the list is the result, not the function, in your case it is None because your functions doesn't have any return values.

Upvotes: 0

jme
jme

Reputation: 20695

Just omit the parens:

tier_1_questions = [question_1, question_2]

If you include the parenthesis, the function body is executed. That's why you still see the questions being printed, even after you remove print tier_1_questions[0].

To evaluate the function, then, you'll do this: tier_1_questions[0](). Or, to evaluate every function in the list, for example:

for question in tier_1_questions:
    question()

Upvotes: 1

kojiro
kojiro

Reputation: 77089

Python functions are objects. The parentheses are just how you invoke them. If you remove the parentheses, they're just named objects.

>>> def foo():
...   pass
... 
>>> def bar():
...   pass
... 
>>> [foo, bar]
[<function foo at 0x10fe9b9b0>, <function bar at 0x10fe9bde8>]

To invoke them from the list, just add the parentheses back:

>>> def baz():
...   print("hello, world")
... 
>>> [foo, baz, bar][1]()
hello, world

Upvotes: 4

Related Questions