[Tutor] random.choice()

Cédric Lucantis omer at no-log.org
Tue Jul 1 14:52:11 CEST 2008


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()'. 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()

-- 
Cédric Lucantis


More information about the Tutor mailing list