Derek Cheng
Derek Cheng

Reputation: 43

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

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.

Upvotes: 3

Views: 4551

Answers (5)

Nishant Chaudhary
Nishant Chaudhary

Reputation: 1

The random.choice method only takes 1 parameter but you give 6 but you can try this:

import random

def rollDie():
    return random.choice((1,2,3,4,5,6))
    # - or -
    # return random.choice([1,2,3,4,5,6])
    # - or -
    # return random.randint(1,6)
    # - or -
    # return random.randrange(1,7)

print(rollDie())

Upvotes: 0

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

Upvotes: 0

Red
Red

Reputation: 27557

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)

Upvotes: 2

Vicente Lineros
Vicente Lineros

Reputation: 11

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

Upvotes: 1

Brad Solomon
Brad Solomon

Reputation: 40878

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.

Upvotes: 3

Related Questions