Please help with this

Peter Otten __peter__ at web.de
Wed Nov 13 07:30:16 EST 2013


mkharper wrote:

> Hi Saad,
> 
> I've had a play and the following "does something".
> (I'm running Python 2.7 so replaced input with raw_input.)
> (User can use upper or lower case, just lower it before test.)
> (I simplified the questions/answers so I could answer them.)
> 
> I'm out of time but hope the following helps.
> 
> Kind regards,
> 
> 
> Michael
> 
> 
> #!/usr/bin/env python
> """
>     This is a game where you have to escape a dragon.
>     By Saad Imran
> 
> """
> 
> import random
> import pygame
> 
> # Define questions and answers.
> 
> QUE = {1: "4 x 2",
>        2: "3 x 6",
>        3: "2 x 5",
>        4: "6 / 2",
>        5: "7 + 7",
>        6: "8 - 3",
>        7: "5 x 5",
>        8: "4 / 1",
>        9: "0 x 6", }
> 
> ANS = {1: "8;75;75",
>        2: "18;75;75",
>        3: "10;75;75",
>        4: "3;75;75",
>        5: "14;75;75",
>        6: "5;75;75",
>        7: "25;75;75",
>        8: "4;75;75",
>        9: "0;75;75", }
> 

> # Code to generate random number
>             QUESEL = random.randrange(1, 10)

You can simplify that some more by putting question/answer pairs into a list

qa_pairs = [
    ("What is 4 x 2? ", "8"),
    ("What is 3 x 6? ", "18"),
    #...
]

and then use random.choice() and tuple unpacking

question, answer = random.choice(qa_pairs)

if input(question) == answer: # python 2: replace input with raw_input
    print("correct")
else:
    print("UH-OH!")

You can nest the tuples if you really need other data

qa_pairs = [
    ("What is 4 x 2? ", ("8", 75, 75)),
    ("What is 3 x 6? ", ("18", 75, 75)),
    #...
]

question, answer_and_offset = random.choice(qa_pairs)
answer, userx, dragonx = answer_and_offset
#...




More information about the Python-list mailing list