简体   繁体   中英

Python trivia game

I want to make a trivia game using 2 arrays or lists. How do you link items from one list to another? I have this code:

import random

mylist = ['A','B','C']
answer = ['1','2','3']
value = random.choice(mylist)
print (value)
input()
mylist.remove(value)
value = random.choice(mylist)
mylist.remove(value)
print (value)
input()
value = random.choice(mylist)
print(value)
mylist.remove(value)

I know how to randomly choose a variable from mylist (the questions) but how do I represent A as 1 and have the user input 1 for it to be correct?

How do I link one list to another and make a trivia game? It needs to ask a question and then the user inputs answer. If correct, they get a point and after 4 questions it asks them if they want to play again and then 4 new questions for 3 rounds and there has to be a score kept of how many they got right.

This program is right on the borderline between being acceptable as a list/dict of lists and being better off written with classes. If there's any possibility that it will grow, you'd probably want to reorganize it as an object oriented program (OOP), like this:

import sys
import random

class Question(object):
    def __init__(self, question, answer, options):
        self.question = question
        self.answer = answer
        self.options = options

    def ask(self):
        print self.question + "?"
        for n, option in enumerate(self.options):
            print "%d) %s" % (n + 1, option)

        response = int(sys.stdin.readline().strip())   # answers are integers
        if response == self.answer:
            print "CORRECT"
        else:
            print "wrong"

questions = [
    Question("How many legs on a horse", 4, ["one", "two", "three", "four", "five"]),
    Question("How many wheels on a bicycle", 2, ["one", "two", "three", "twenty-six"]),

    # more verbose formatting
    Question(question="What colour is a swan in Australia",
             answer=1,
             options=["black", "white", "pink"]),    # the last one can have a comma, too
    ]

random.shuffle(questions)    # randomizes the order of the questions

for question in questions:
    question.ask()

That puts the logic of how the data structure is used closer to where the data structure is defined. Also (addressing your original question), it's easy to associate questions with answers because they're no longer in separate lists.

There's no incentive not to do this because Python doesn't require much extra work to make a class. This is approximately the same length as the dict-of-lists solution (on which it was based), and is arguably easier to read, closer to you had in mind before you sat down to start programming. I often use classes even in four-line programs: OOP doesn't have to be a big deal.

Edit: You can manipulate the list of class instances the same way you'd manipulate a list of integers or strings. For example,

del questions[0]

removes the first item from the list,

questions.append(Question("What is a new question", 1, ["This is."]))

adds a new question to the end of the list, pop lets you use the list as a stack, etc. (See a Python tutorial for more.) If you want to remove specific questions using list's remove method, rather than removing it by index (what del does), then you'll need to tell Python what it means for two questions to be the same.

Try adding these two methods to the class:

    def __eq__(self, other):
        return self.question == other.question

    def __repr__(self):
        return "<Question: %s? at %0x>" % (self.question, id(self))

The first defines two Question instances to be equal if their question strings are the same. You could extend the definition by also requiring their answers to be the same, but you get the idea. It allows you to do this:

questions.remove(Question("How many legs on a horse", 0, []))

to remove the legs-on-a-horse question.

The second pretty-prints the question objects on the Python command-line, so that you can see what you're doing when you experiment with these commands. The best way to learn is by trial-and-error, and this makes trial-and-error more productive.

Use an array of arrays.

One array per question

In each array the first element is the question, the second the index of the correct answer and the remainder are the possible answer options

I have not randomized the questions as you can already do this

import sys

questions=[
  ['How many legs on a horse',4, 1, 2, 3, 4 ,5],
  ['How many wheels on a bicycle',2,'one','two','three','twenty six'],
  ['What colour is a swan in Australia',1, 'black', 'white', 'pink']
  ]

for ask in questions:
    print ask[0]+'?'
    n = 1
    for options in ask[2:]:
        print "%d) %s" % (n,options)
        n = n + 1
    response = sys.stdin.readline().strip()
    if int(response) == ask[1]:
        print "CORRECT"
    else:
        print "wrong"

Alternatively, in line with suggestion below in comments (thanks Don) use a dict.

import sys

questions = [
  {
  'question': 'How many legs on a horse',
  'answer': 4,
  'options': [1, 2, 3, 4, 5]},
  {
   'question': 'How many wheels on a bicycle',
   'answer': 2,
   'options': ['one', 'two', 'three', 'twenty six']},

  {
   'question': 'What colour is a swan in Australia',
   'answer': 1,
   'options': ['black', 'white', 'pink']}
  ]

for ask in questions:
    print ask['question'] + '?'
    n = 1
    for options in ask['options']:
        print "%d) %s" % (n, options)
        n = n + 1
    response = sys.stdin.readline().strip()
    if int(response) == ask['answer']:
        print "CORRECT"
    else:
        print "wrong"

hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM