[Tutor] How to run a .py file or load a module?
Eric Dorsey
dorseye at gmail.com
Mon Apr 27 00:06:49 CEST 2009
Dayo,
I modified the code a little bit to make things work the way I think you
meant it to work(hopefully), and I changed the name of the function so that
its' not the same name as the python file itself, but hopefully this answers
your questions. Here is my countdown.py
def launchme(n):
while n > 0:
print n
n -= 1
else:
print 'Blastoff!'
#uncomment to run from the shell
#launchme(7)
So, assuming we're running the interpreter from the same folder that
countdown.py is in. You have to call module.function(parameter)
>>> import countdown
>>> countdown.launchme(4)
4
3
2
1
Blastoff!
>>>
If we uncomment the "#launchme(7)" line, and run it from the shell:
$ python countdown.py
7
6
5
4
3
2
1
Blastoff!
On Sun, Apr 26, 2009 at 3:35 PM, Dayo Adewunmi <contactdayo at gmail.com>wrote:
> 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
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090426/0b9a71b2/attachment.htm>
More information about the Tutor
mailing list