Skip to content Skip to sidebar Skip to footer

Selecting A Random Number Within A Series(python)

I'm trying to create a program that picks a random number out of a series of 2 numbers, does anyone know how this is done? I looked it up and said to use the choice function, howev

Solution 1:

As the documentation states, just write choice((1, 5, 9, 27)).

If you write choice(1, 5, 9, 27), that is passing four arguments to the function.

If you write choice((1, 5, 9, 27)), that is passing a single argument, a tuple of four elements, (1, 5, 9, 27), to the function.

Solution 2:

The error message is a bit misleading. random.choice(seq) takes a sequence. You can pass it an object like a list of values, or a tuple - anything that supports indexing.

If you want to pass it two values, a and b, you'll have to wrap them in something indexable. Try choice([a,b]) or choice((a,b)). This first creates a list or tuple with two items and then passes that to the choice function.

A more explicit notation for the same thing is:

seq = (a,b)
variable = choice(seq)

Post a Comment for "Selecting A Random Number Within A Series(python)"