[Tutor] function declaration problems perhaps?
Alan Gauld
alan.gauld at btinternet.com
Wed Jul 25 10:37:47 CEST 2007
"nibudh" <nibudh at gmail.com> wrote
> I looked over my code (all 41 lines!) and couldn't find anything,
> then on a
> hunch i moved the def statement _above_ the rest of my code and hey
> presto
> it worked.
>
> I vaguely understand why this is happening, but can someone explain
> it to
> me.
Its pretty simple.
Python processes the file top to bottom. If it comes upon
a name that it doesn't recofgnise it generates an error.
Thus:
#############
print foo(42)
def foo(x):
return x * 2
##############
will generate an error because at the point where the print
statement tries to execute foo(42), foo does not exist!
This is one good reason to avoid putting executable code in the
main body of a file but to always wrap it in a function like so:
##############
def main()
print foo(42)
def foo(x):
return x * 2
if __name__ == "__main__": main()
###############
Now the code doesn't get executed until the last line of the file
by which time all definitions have been executed and the
program will work correctly.
This also makes the module inherently more reusable since it
can be imported without the main code being executed (the purpose
of the if expression.)
HTH,
--
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