[Tutor] defining functions

Kalle Svensson kalle@gnupung.net
Mon, 10 Dec 2001 08:50:15 +0100

[Kirk Bailey]
> Gang, in some languages you MUST define somethign before usign it, in others
> no, as long as it is defined SOMEPLACE, the language will find it and be
> cognisant of it (perl for instance). Must I list all definitions ABOVE the
> code using them in python, or can I bury them in the bottom? And do I have
> to take precautions to ensure the program does not execute them as it corses
> through the file? For instance, in BASIC, I must ensure the thing exits
> before it arrives at lines defining subroutines ( ancestral opbjects). If it
> falls through the end of the program to these definitions, it trys to
> execute them- then arrives at a return and BARFS IT'S COOKIES beause there
> was no matching gosub. In PASCAL one must define anything and everything
> before using it- a true BONDAGE AND DISIPLINE language If I ever avoided
> one. Gimmee a clue or two on these issues, would you?

In python, things must be defined before they are used.
For example:

>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'i' is not defined
>>> i = 1
>>> i

This doesn't necessarily mean that the definition must come earlier in the
source file than use, just in the control flow:

def f():
    print foo
foo = 1

is perfectly valid.

def f():
    print foo
foo = 1

is not.

Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]