Reputation: 1179
I made a simple mistake in the following die roll function:
import random
def rollDie():
return random.choice(1,2,3,4,5,6)
print(rollDie())
I do know that I need to pass the sequence as a list or tuple, but I was more curious about the following error message.
Traceback (most recent call last):
File "Lecture 5.2 -- stochastic - die roll example.py", line 8, in <module>
print(rollDie())
File "Lecture 5.2 -- stochastic - die roll example.py", line 6, in rollDie
return random.choice(1,2,3,4,5,6)
TypeError: choice() takes 2 positional arguments but 7 were given
The message says "choice() takes 2 positional arguments but 7 were given".
But the documentation indicates only one argument (sequence). https://docs.python.org/3/library/random.html
What is the second argument (or seventh in my case)? Is this the seed (which I have not specified so is being initialised by the clock)?
Upvotes: 2
Views: 7530
Reputation: 1
you must give your value's in the form of a list or tuple:
List:
import random
def rollDie():
return random.choice([1,2,3,4,5,6])
print(rollDie())
Tuple:
import random
def rollDie():
return random.choice((1,2,3,4,5,6))
print(rollDie())
This error is because the code thinks that you give each of these numbers as an argument. the choice is an inbuilt function that randomly selects data from an iterator of data.
Upvotes: -3
Reputation: 7
To fix the code do this:
import random
options=[1,2,3,4,5,6]
def rollDie():
return random.choice(options)
#whenever you use choice you must put the options in a list since choice only takes one argument.
print(rollDie())
Upvotes: -1
Reputation: 2998
As per my experience : random.sample is better solution than random.choice.
Upvotes: -1
Reputation: 1121744
choice()
is a method on the hidden Random()
instance the random
module maintains. Because it is a method, it has 2 arguments: self
and the iterable from which to make a choice.
From the module documentation:
The functions supplied by this module are actually bound methods of a hidden instance of the
random.Random
class.
and the random
module source code:
def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') from None return seq[i]
Upvotes: 8