JeromJaison
JeromJaison

Reputation: 15

How to choose random value of a list 5 times and give a different value each time

I am new to python, so forgive me if my question seems dumb. I am trying to make a program that asks a different math question each time in a for loop which is set to repeat 5 times. But I am kinda stuck here. It repeats the same question each time the for loop is run but I am trying to show a different question each time. Is there any way in which it's possible to do it the way I want?

qst = random.choice(qsts)
crt = 0
for x in range(5):
    x += 1
    print("Question " + str(x))
    print(" ")
    print(qst)

Upvotes: 0

Views: 1228

Answers (3)

Lecdi
Lecdi

Reputation: 2241

Placing the line that gets a random question inside the for loop might work a bit better, but it's still not the best solution as the same question might randomly get picked twice.

You are better off using random.sample to get five elements which are guaranteed all to be unique.

Here is the code:

random_qsts = random.sample(qsts, 5)
crt = 0
for i, q in enumerate(random_qsts, 1):
    print(f"Question {i}: {q}")

This code gets all five random questions first, outside of the loop, and then iterates over them, asking each one.

This way, no question will be repeated twice.

Upvotes: 0

Adon Bilivit
Adon Bilivit

Reputation: 26943

Use the random module to shuffle or sample the list of questions. You can then iterate over the list sequentially. For example:

from random import shuffle

qsts = ['How high is mount Everest',
'Will England ever win the World Cup',
'Is a tomato a fruit',
'Do you like cabbage',
'Is Windows a terrible operating system']

shuffle(qsts)

for i, q in enumerate(qsts, 1):
    print(f'Question {i}: {q}?')

Or, if you don't want the qsts list to change...

from random import sample

qsts = ['How high is mount Everest',
'Will England ever win the World Cup',
'Is a tomato a fruit',
'Do you like cabbage',
'Is Windows a terrible operating system']

for i, q in enumerate(sample(qsts, k=len(qsts)), 1):
    print(f'Question {i}: {q}?')

Output sample:

Question 1: How high is mount Everest?
Question 2: Do you like cabbage?
Question 3: Will England ever win the World Cup?
Question 4: Is a tomato a fruit?
Question 5: Is Windows a terrible operating system?

Upvotes: 0

ndc85430
ndc85430

Reputation: 1745

You only ever make a choice once, outside the loop. You need to do move that first line into the loop so it's run on each iteration.

Upvotes: 2

Related Questions