I want to make a trivia game in python. Let's say I have a set of 25 questions, how do I choose 10 random questions from that set without repeats?

Recommended Answers

All 3 Replies

import random
questions=open('file_containing_the_questions_separated_by_newline.txt').readlines()
print random.sample(questions,10)

I want to make a trivia game in python. Let's say I have a set of 25 questions, how do I choose 10 random questions from that set without repeats?

commented: good help +13

Which can be expressed also:

import random
with open('file_containing_the_questions_separated_by_newline.txt') as question_file:
    my_questions = random.sample(list(question_file), 10)

You may want to strip off the newline character ...

'''file "Questions101.txt" could look like this ...
Which animal has three hearts?
What is Captain Kirks middle name?
Which country has the most Dentists?
What type of organism causes malaria?
What was the first brand name for Bubble Gum?
Which game uses the phrase "en passant"?
What do you call one golf stroke over par?
An entomologist is a specialist in ....
An ornithologist studies ....
Who was never elected president or vicepresident?
Who was Langston Hughes?
Which is the most common word in the English language?
What was Paul Revere's occupation?
Where do you find more than one quarter of earth's forests?
In what country was bowling invented?
'''

import random
import pprint

def pick_ten(fname):
    question_list = []
    for question in open(fname):
        # strip off new line character
        question = question.rstrip()
        question_list.append(question)
    return random.sample(question_list, 10)


# testing ...
filename = "Questions101.txt"
question_list = pick_ten(filename)
pprint.pprint(question_list)

'''possible result>>>
['Who was Langston Hughes?',
 'What was the first brand name for Bubble Gum?',
 'What type of organism causes malaria?',
 'Which game uses the phrase "en passant"?',
 'Which is the most common word in the English language?',
 'An ornithologist studies ....',
 'An entomologist is a specialist in ....',
 'What do you call one golf stroke over par?',
 "Where do you find more than one quarter of earth's forests?",
 'Who was never elected president or vicepresident?']
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.