about functions question
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Oct 25 09:35:38 EDT 2007
NoName a écrit :
> sorry! Yes it's work.
> What about 2 question?
> Can i put function after main block?
>
> print qq()
>
> def qq():
> return 'hello'
Where's your "main block" here ?
> Traceback (most recent call last):
> File "C:\Python25\projects\indexer\test.py", line 1, in <module>
> print qq()
> NameError: name 'qq' is not defined
Indeed. When the code is loaded in the interpreter (that is, when passed
as a script or when imported as a module), all top-level statements are
executed sequentially. This creates all the function and class objects
and populate the module's namespace accordingly.
>
> Or onli possible:
>
> def main():
> print qq()
>
> def qq():
> return 'hello'
>
> main()
>
The canonical case for small scripts is to have first all functions and
globals defined, then the main code protected by a guard, ie:
import something
SOME_CONST = 42
def do_something():
pass
def try_something_else():
pass
if __name__ == '__main__':
print SOME_CONST
if not do_something():
try_somethin_else()
For bigger apps, you usually define all functions and classes in
modules, so the 'main' script doesn't define much - just do the needed
imports, and call the appropriate function or class.
More information about the Python-list
mailing list