[Tutor] Newbie Project part 2...

Alan Gauld alan.gauld at btinternet.com
Sat Jul 14 21:38:58 CEST 2007


"Tony Noyeaux" <tnoyeaux at msn.com> wrote in
---------------------------------------------------------
import random
print "\t\t\t\tLife Simulator"
print "You have just turned 18 years old. Your life awaits,... choices 
to be made.."
print "\na)Army,\nb)Navy,\nc)Airforce"
job=raw_input("What will u join?")
if job == "a":
    print random.choice(["You win Silver star", "You are killed in 
action"])
elif job == "b":
    print random.choice(["You fall overboard", "You command you're own 
battleship"])
elif job == "c":
    print random.choice(["You get shot down", "You become wing 
commander"])

raw_input("\n\nPress Enter to quit.")
----------------------------------------------------------------------

> This works fine.
>
> I am having trouble coding in the 2nd question,.. and all subsequent 
> questions.
>
> The next Question.. has to be a result of the random result.

I suggested using a nested dictionary structure to hold the questions.
Did you try that? It should make this a relatively trivial problem.

I'll show the structure for the example you have given so far:

questions: {'Q':
                    {"""
You have just turned 18 years old.
Your life awaits,... choices to be made..
""" : ['Army', 'Navy', 'Airforce']}
                 {'a':
                     { 'Q': {#army questions here}
                     }
                  'b':
                    {
                     'Q': {''What kind of ship?': 
['battleship','carrier','tug']},
                     'a': {  # battleship questions},
                     'b': { # carrier questions},
                     'c': { # tug questions }
                     }
                  'c':
                    {  'Q': {# airforce Q here}
                    }
                }

Obviously keeping the structure clear is critical to success and
a good programmers editor will help balance the braces/quotes etc

You can extend the structure to have multiple questions at each
stage by simply putting each questoon/answer dictionary in a list.
You could also break the structure to ease layout so for example
three separate instances, one per service. You could
even encapsulate it in a class (I would!)

You are essentially building a tree structure and then navigating
down it in a part-random, part-deterministic manner.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list