[Tutor] My First Program

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Dec 8 22:52:54 CET 2005


> > Hi! My first "ever" program that I've created is a simple game called
> > "State Capitals". It's straight forward; 5 simple questions about
> > state capitals in a non-GUI format.

[some code cut]

Hi Trent,


Looks good so far!  There is one direct thing we can do to make the
program a little shorter: we can use "functions".  If you want, we can go
through an example to see what these things do.


There's a fairly consistant pattern to each of the quiz questions.  If we
look at the first two blocks of questions, for example:


> > question = raw_input("Question 1 - What is the capital of NC, a: Raleigh
> > or
> > b: Atlanta? ")
> > if question == "a":
> >         print "Yes\n"
> > else:
> >         print "WRONG\n"


> > question = raw_input("Question 2 - What is the capital of SC, a:
> > Greenville
> > or b: Columbia? ")
> > if question == "b":
> >         print "Yes\n"
> > else:
> >         print "WRONG\n"


and if we squint our eyes a bit, we might see a pattern here, something
like:

    question = raw_input(  {some question here}  )
    if question ==  {some right answer here}:
        print "Yes\n"
    else:
        print "Wrong\n"

where I've put placeholders (the stuff in braces) to mark the places
that are different.


There is a feature in many programming languages called the "function"
that allows us to capture this pattern and give it a name.  Think Mad
Libs: what we can do is make a mad-lib game form, and then let people fill
in what they want.

The block above can be turned into this function:

###################################################
def quiz_question(some_question, some_right_answer):
    question = raw_input(some_question)
    if question == some_right_answer:
        print "Yes\n"
    else:
        print "Wrong\n"
###################################################


'quiz_question' is the name I've given this, though if you want to call
it something else, please feel free to change the name.


Once we have 'quiz_question', how do we use this?  Let try this from the
interactive interpreter:

######
>>> quiz_question("what's your favorite color?", "green")
what's your favorite color?green
Yes

>>> quiz_question("what's your favorite color?", "green")
what's your favorite color?blue no red!
Wrong
######


Does this make sense so far?

By having that function, it'll lets you add more questions to your quiz by
just adding the stuff that's really important: the content of the
questions and their right answers.


The tutorials on:

    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

should talk about functions a bit.  Try playing with functions: it should
make your program shorter, and that'll make it a little easier to think
about how to do the three-strikes-you're-out! thing.



More information about the Tutor mailing list