Reputation:
I'm making a small program (quizz) to test this language and i'm stuck in a function So let me explain I want to receive values from my database, then use only 5 of them, so for every question, the user answer, and move to the next question until reaching the last one. The code i have so far is
def escolhaFinal(id_tema, id_tipo):
cur = conn.cursor()
cur.execute("SELECT question,op1,op2,op3,op4,correto FROM questions where id_tema = %s and id_grau = %s", (id_tema,id_tipo))
data = cur.fetchall()
l = list(data)
random.choice(l,5)
for row in l:
print(l)
cur.close()
conn.close()
But i receiving this error TypeError: choice() takes 2 positional arguments but 3 were given
any help regarding this function?
Upvotes: 0
Views: 2873
Reputation: 19806
From the documentation of random.choice()
you have:
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
To select more than one element, you can either use a list comprehension like this:
[random.choice(l) for i in range(5)]
Or random.sample()
to select unique elements:
random.sample(l, 5)
Output:
>>> import random
>>>
>>> l = [1, 2, 3, 4, 5]
>>> random.sample(l, 3) # unique elements
[4, 2, 5]
>>>
>>> [random.choice(l) for i in range(3)] # Note that we have 3 twice!
[3, 5, 3]
Upvotes: 1
Reputation: 36504
It looks like you want to be using random.sample
instead, because that allows you to return more than a single randomly selected item from your list, like:
>>> import random
>>> myList = range(100)
>>> winners = random.sample(myList, 5)
>>> print winners
[79, 10, 32, 98, 82]
>>>
Upvotes: 1
Reputation: 1337
random.choice takes only 1 parameter. In your code
random.choice(l,5)
what is the 5 supposed to do? The documentation states for choice: "Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError."
so change the line to use only 1 parameter and assign the value to use it later (aka adjust the rest of your code).
Upvotes: 0