Dick Moores wrote:
At 05:43 AM 7/1/2008, Tim Golden wrote:
Dick Moores wrote:
So I want to randomly choose between them. I thought that I might be
able to use choice() to do that. So,
(bunch of functions here)
if __name__ == '__main__':
choice([use_for_float_demo(), use_for_integer_demo()])
I find that what's gets run each time is BOTH of these functions,
first use_for_float_demo(), and then use_for_integer_demo()! What's
going on?
What you *want* to do is choose one of two functions, and call
whichever is chosen:
fn = choice ([a, b])
result = fn ()
What you're *actually* doing is calling two functions, and returning
one result or the other:
result = choice ([a (), b ()])
I'm not sure I understand the distinction. It seems you're saying in
either case I get one result or the other. In fact, each time I run the
program, I get BOTH results.
Let's talk through what the Python interpreter's doing in each case:
a) fn = choice ([a, b]); print fn ()
Here, the interpreter is saying: ok, let's build a list which contains
two functions. Now, let's pick one of those functions. Whichever one
we picked, let's call it and print out the result.
b) print choice ([a (), b ()]
In this case, the interpreter is saying: build a list containing *the result*
of calling each of these functions, so both functions are called when the
list is built, and the list contains [<result of calling a>, <result of calling
b>].
Now pick one of those results and display it.
Is that any clearer? If not, I'm obviously not too good at explaining this
kind of thing; maybe someone else can have a go.
TJG
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor