Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 318
Derek Cheng Avatar asked Oct 13 '25 00:10

Derek Cheng


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

like image 91
Brad Solomon Avatar answered Oct 14 '25 13:10

Brad Solomon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!