[Tutor] Return to main menu [use functions to collect related statements together, not modules]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jun 29 02:29:47 EDT 2004



On Tue, 29 Jun 2004, K J wrote:

> Well this is the little program that I have created it is my first one
> and it works just fine from what I have tested. Only problem I have with
> it is that, lets say you enter 1 at the prompt it will load the add.py
> modual. however when it comes to the end of the modual it terminats. How
> would I go about making it so that it will return to the menu and ask
> for another choice.


Hi Kevin,

Ah, I see.  It looks like you're using module import to try to execute
another program.  You have the right idea, but it'll only work once,
because of the way that Python avoids reading the same module twice.


You'll notice this problem if you change your main program to something
really simple like:

###
import add
import add
import add
###

The program that's in 'add' will execute the first time... and do
absolutely squat for the next two import statements.  *grin*


The issue is that the program above is trying to use modules to execute a
bunch of statements together, but that's not exactly what they supposed to
be used for.  Instead, we should be using a "function": functions are the
basic tools for grouping a bunch of program statements together.


Here's an example of a function:

###
>>> def sayHello():
...     print "hello world"
...
>>> sayHello()
hello world
>>> def sayHelloTwice():
...     sayHello()
...     sayHello()
...
>>> sayHelloTwice()
hello world
hello world
###

The 'def' here allows us to create a named function, and we define what
should happen when we call the function.

If you put everything that's in your 'add' module, and move it into a
function, then your program should behave the way that you expect.

(Just for your information: modules are used to group related functions
together, so it's just a different kind of grouping than the one you were
expecting.)


I feel that functions are more fundamental than modules, so I'd recommend
learning them cold; they'll serve you well.  If you want to learn more
about functions, you may find something like 'How to Think Like a Computer
Scientist' useful:

    http://www.ibiblio.org/obp/thinkCSpy/chap03.htm

The other tutorials on:

    http://www.python.org/topics/learn/non-prog.html

also should cover functions; feel free to ask questions about them here.


Hope this helps!




More information about the Tutor mailing list