Selecting a random number within a series(python)

2019-08-05 05:14发布

问题:

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, however an error came up saying I had given 3 arguments when the code needed only 2.

What do I have to do to make it pick a random number in a series?

variable = [choice(a,b),choice(a,b)]
variable = choice(1,5,9,27) #  variable should now = 1, 5, 9 or 27.

回答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.



回答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)


标签: python random