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.
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.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])
orchoice((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: