This isn't recursive

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Tue Feb 19 23:11:10 EST 2002


Jason <caljason76 at yahoo.com> wrote:
: # Ummm... I think the posted wanted a recursive solution.
: #
: # I am a Python novice so I don't really understand how things
: # work, yet.  So some of this may either be wrong or not the
: # Python way.  Also I have no idea why the 'if __name__ == ...'
: # construct is needed instead of just the naked main statements.

Python files don't necessarily have main() functions; when Python
processes a file, it actually executes the code as-is.  That is,
things like 'def' are actual statements in the language.  This makes
certain dynamic things possible, like this:

###
choice = raw_input("numeric or verbal?")
if choice == 'numeric':
    def yes(): return 1
else:
    def yes(): return 'Yes!'
print yes(), "master"
###

If you're familiar with Scheme, you will feel quite at home.  *grin*


The "__name__ == '__main__'" expression is true only when we're
running a file as a standalone Python program.  If we 'import' a file
as a module, however, things are quite different.  Here's an example:

###
[dyoo at hkn dyoo]$ cat hello.py
print "Hello, my name is", __name__
[dyoo at hkn dyoo]$ python hello.py
Hello, my name is __main__
[dyoo at hkn dyoo]$ python
Python 1.5.2 (#1, Feb  1 2000, 16:32:16)  [GCC egcs-2.91.66 19990314/Linux (egcs- on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import hello
Hello, my name is hello
>>> 
###

Variables with double underscores around them should be considered
special varaibles that are set up by the Python runtime system.


: # Also, can somebody help me find the documentation to the builtin
: # procedures, like print().  I checked the __builtin__ module docs
: # but there is nothing there.  Thanks

You can find documentation on the builtin functions here:

    http://python.org/doc/lib/built-in-funcs.html

However, you won't find 'print' in there because Python's print is a
statement; it's not a function but a "special form".  There are
reasons for this: it allows for a simplified syntax for printing
things.


: # -j (nordwick at xcf.berkeley.edu)

Nice to see another person from Berkeley!  *grin*

Good luck to you!



More information about the Python-list mailing list