random.choice() takes 2 positional arguments but 3 were given

Viewed 1812

When I type this:

rand_num = random.choice(1, 101)

It shows:

TypeError: choice() takes 2 positional arguments but 3 were given

These are all put in functions and I don't get why it says this.

4 Answers

The signature for random.choice() is:

choice(seq)

You pass it a sequence such as:

>>> random.choice([1, 2, 6, 8, 9])
2

A range object is also valid as shown in the other answer here.

You might logically ask, why does Python tell you that choice() takes 2 positional arguments rather than just one (seq)? That's because choice() implicitly takes a self parameter since it's an instance method. But for your intents and purposes as the function caller, you're expected to pass just one argument, which is a sequence, such as a list or tuple.

It may seem strange that the error says 3 arguments were given when you only put in 2, but what you might not know is that the random.choice() method is actually a bound method of a random.Random() object.

So when the error says but 3 were given, they are including the self parameter that you didn't pass in. Here is a demonstration of a more clear scenario for the error:

obj = random.Random()
rand_num = random.Random.choice(obj, 1, 101)

Output:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    random.Random.choice(obj, 1, 101)
TypeError: choice() takes 2 positional arguments but 3 were given

The way to fix it is simple; pass the 1 and 101 into the range() method to convert the two numbers into a single element:

rand_num = random.choice(range(1,101))

But the more practical method would be to use the random.randint() method:

rand_num = random.randint(1,100)

I think that you want to do:

rand_num = random.choice(range(1,101))

The docs says that you must pass a sequence to choice() (in this example, a range).

Choice makes a random choice from a given direct, such [1,2,3,4,5....]
Seeing what you need:

  1. if you choose something random from the list then:
    rand_num = random.choice([1,2,3,...., 101])

  2. if you need a random number from 1 to 101, such that a <= rand_num <= b - then use randint: rand_num = random.randint(1, 101) or you may use standard function range(start, stop, step)
    rand_num = random.choice(range(1, 101, 1))

Related