[Tutor] How to run a .py file or load a module?

Dayo Adewunmi contactdayo at gmail.com
Sun Apr 26 23:35:36 CEST 2009


I'm looking at recursion in "Think Python", and this is the bit of code:


#!/usr/bin/env python

def countdown(n):
        if n <= 0:
                print 'Blastoff!'
        else:   
                print n
                countdown(n-1)


I've typed that in vim and saved as countdown.py, but I'm not sure how 
to run it. I've had other
python files, where the triggering function didn't take any arguments,
so I would just put a `foo()` at the end of the .py file.

However with this particular function that requires an argument, I'm not
sure how to run it. I've had to type it out in the python prompt and 
then call
the function with an argument. That works, naturally.

I've also tried this:

        >>>import countdown
        >>>countdown(10)

but this is the error I get:

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

How can I

a) Open my shell, and do something like: $ python countdown.py   
but have it take an argument and pass it to the function, and execute.

b) Import the function in the interactive interpreter, and call it like so:

        countdown(10)

without getting the abovementioned error.
Thanks.

Dayo


More information about the Tutor mailing list