problem using using list with function

Ken Seehof kseehof at neuralintegrator.com
Wed Oct 10 19:08:41 EDT 2001


Things have to be defined before they can be used.  For example:

print x  # raises NameError exception
x = 5

Of course, this won't work since x is used before it is defined.
In python, function definitions are executed at runtime, so a
def statement is analogous to an assignment such as x=5.

If you are used to compiled languages you might have expected
different behaviour since compilers usually process function
definitions before runtime.

In python, functions are objects just like everything else.

Now this won't be surprising:

f()    # raises NameError exception
def f():
    print 'foo'

adam griffin wrote:
> I think I figured out my problem. I had the function definition at the end
> of my script when I put it at the beginning it worked. is this the only
> place you can put definitions?
>
> "Ken Seehof" <kseehof at neuralintegrator.com> wrote in message
> news:mailman.1002701769.4408.python-list at python.org...
> > > i'm trying to write a function that takes a list as it's only
arguement
> > and
> > > also has a list as it's return value. this is sort of what it looks
> like:
> > >
> > > list1 = [ 1, 2, 3];
> > >
> > > list2 = function(list1)
> > >
> > > def function(listArguement):
> > >     #statements...
> > >     return list
> >
> > Looks like you are on the right track.  Try this in your python
> interpreter.
> > You can learn a lot by trying things in the interpreter to see what
> happens.
> >
> > >>> def spam_and(a):
> > ...  b = ['spam', 'spam'] + a
> > ...  return b
> > ...
> > >>> list1 = [ 1, 2, 3]
> > >>> list2 = spam_and(list1)
> > >>> print list2
> > ['spam', 'spam', 1, 2, 3]






More information about the Python-list mailing list