[Tutor] Running Python from UNIX
alan.gauld@bt.com
alan.gauld@bt.com
Tue, 6 Aug 2002 17:37:41 +0100
> environment. I wrote a small function to compute fibonacci series.
> If I write this as a script and execute the script,
> it runs without errors but does not print the result.
My guerss is that in the script file you have
defined the function but not executed it.
######### foo.py ########
# define function foo
def foo():
print 'foo'
# now execute it
foo()
######## End of foo.py ########
Without the foo() line when you run the script the
function foo will be defined but not executed.
To allow you to import the script or execute it we
usually add the following bit of magic syntax at
the end of the file:
if __name__ == "__main__":
foo()
then you can import foo and define but not execute
the function or run it as a script in its own right
in which case foo() will be executed too.
> code the same function as a regular program,
> then it works as a script too.
Thats because its now not a function so each
line gets executed when the file runs.
HTH,
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld