[Tutor] random.choice()
Dick Moores
rdm at rcblue.com
Tue Jul 1 15:08:57 CEST 2008
At 05:52 AM 7/1/2008, Cédric Lucantis wrote:
>Le Tuesday 01 July 2008 14:38:36 Dick Moores, vous avez écrit :
> > I'm writing a demonstration version of a program which does things
> > with integers, and with floats, which are randomly generated. I want
> > to also randomly pick whether the integer side, or the float side is
> > demonstrated next. I have 2 functions, use_for_integer_demo()
> > and use_for_float_demo(), and one or the other of these will start
> > the demo. 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()])
> >
>
>Writing this [use_for_float_demo(), use_for_integer_demo()] calls the two
>functions and build a list with their returned values. So the choice is
>between 'the result of use_for_float_demo()' and 'the result of
>use_for_integer_demo()'.
But why do I see BOTH results each time I run the
program? There's no random choice made. (I already asked Tim Golden this.)
>This explains why the two functions are called. You
>should rather use function objects like this:
>
># choose a function (note there are no () after the names)
>func = choice([use_for_float_demo, use_for_integer_demo])
>
># then call it
>func()
I didn't realize that I should leave off the ().
Thanks. (And to Tim Golden also.)
DIck
More information about the Tutor
mailing list