[Tutor] Trivia

Alan Gauld alan.gauld at btinternet.com
Fri Jun 24 12:07:31 CEST 2011


"Vincent Balmori" <vincentbalmori at yahoo.com> wrote

> Can you please explain more on what you mean by this?

>> "Your whole approach is very fragile in this respect, it only
>>  takes one small mistake in the data to wreck your program,.

Your program relies on your data being exactly right.
It only takes one missed newline, or one extra newline
or a blank line or an extra question (maybe a cut n paste
error when editing) or whatever to completely mess your
program.

> > Somethjing like a config file format would be much more
> > robust (and readable) the config reader module would make
> > sure you got what you expected back. "

Read the ConfigParser module documentation to see what I mean.
It treats your data like a Windows INI file and you can retrieve
values using section/tag values. So in your case
You could do, in pseudo code:

cp = ConfigParser(filename)
for section in cp.getSections():
     question = cp.get(section, "question")
      points = int( cp.getsection,"points") )
      q1 = cp.get(section,"q1")
      q2 = cp.get(section,"q2")
      etc....

And you can catch exceptions raised to detect errors.

That way, if a value doesn't exist you  find out about it and
the parser handles all the navigation of the file.

You could also use an XML format (or JSON or....) but
Config Parser would be adequate for your needs.

The data file would also be easier to read because
the tags would make it clear:

[Section Title]
tag=value

Becomes, for example:

[On the Run With a Mammal]
points=1
question=Let's say you turn state's evidence and need to "get on the 
lamb." If you wait /too long, what will happen?
q1=You'll end up on the sheep
q2=You'll end up on the cow
q3=You'll end up on the goat
q4=You'll end up on the emu
answer=1
explantion=A lamb is just a young sheep.[The Godfather Will Get Down 
With You Now]...HTH,-- Alan GauldAuthor of the Learn to Program web 
sitehttp://www.alan-g.me.uk/ 




More information about the Tutor mailing list