cannot pass a variable from a function

Larry Bates lbates at swamisoft.com
Wed Jun 16 20:07:54 EDT 2004


Doug,

You are talking about passing by reference.  Python
doesn't do that.  It only passes by value, unless you
pass an object (e.g. list, dictionary, class, etc.).
In those cases you CAN modify object in the function.

For simple operations, just return the value an use
it later (like Fortran functions).

def foo(b)
    return b*1000

c=foo(b)

objects can be passed and modified

def foo(b, l)
    l.append(b)
    return

l=[]
foo(1)
l->[1]
foo(2)
l->[1,2]
foo('test')
l->[1,2,'test']

HTH,
Larry Bates
Syscon, Inc.

"Doug Jordan" <djordan8 at houston.rr.com> wrote in message
news:515Ac.529$M96.246 at fe2.texas.rr.com...
> Kirk,
> Thanks for your input, hoever that is not exactly what I am trying to do.
> I understand that q is local scope.  I was trying to return q and make a
> call to the function using another variable with global scope.
>
> In other language
> subroutine foo(b,c)
>     c=b*1000
> return
> call foo(q,r)
> where q and r are defines and same type as b,c as  function
> How do I do this in python.  I need to perform operations on a variable
and
> pass the new variable to the program.
> Hope this might clear it up.
>
> Doug
> "Kirk Strauser" <kirk at strauser.com> wrote in message
> news:87smcvuma1.fsf at strauser.com...
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> At 2004-06-16T22:46:42Z, "Doug Jordan" <djordan8 at houston.rr.com> writes:
>
> > #function suppose to return variable
> > def fctn2(c):
> >     for h in c:
> >         q=h*80
> >         return q
> >
> > def prntfctn(y):
> >     for j in y:
> >         print j
> >
> > fctn2(list)
> > prntfctn(q)
>
> The name "q" only exists inside the scope of the fctn2 variable.  If you
> want it present inside the global scope, assign it there:
>
>     q = fctn2(list)
>     prtnfctn(q)
>
> That should do what you want.  Note that I'm unaware of any modern
> programming language that would allow a function to assign a value to a
> global variable without explicitly requesting it.  If such a thing exists,
> then I highly recommend you avoid it at all costs.
> - -- 
> Kirk Strauser
> The Strauser Group
> Open. Solutions. Simple.
> http://www.strausergroup.com/
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.4 (GNU/Linux)
>
> iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp
> u44PX2uPlSMGYAV4VG5jaC8=
> =G3qn
> -----END PGP SIGNATURE-----
>
>





More information about the Python-list mailing list