[Tutor] Equivalent of a Subroutine in Python?

Kalle Svensson kalle@gnupung.net
Thu, 1 Feb 2001 19:51:36 +0100


--Dxnq1zWXvFF0Q93v
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Sez Seelinger, Bruce:
> Another question from someone totally new to Python. Is there an equivale=
nt
> in Python to a sub-routine, (e.g. gosub and return).  I want to create a

A function.

[snip]
> best) way to do this is with modules?  A function works but the values
> obtained within the function do not appear to be valid outside of that
> function.  I guess I am looking for the best approach to create the

No.  That's a feature.  Global variables are often a bad idea and make
programs more difficult to understand, especially when they grow larger.
Use class instance methods and variables or plain old return values.

Note:  If you really, really want, use the "global" statement:
>>> a =3D 0
>>> def f(val):
=2E..     global a
=2E..     a =3D val
=2E..=20
>>> print a
0
>>> f(12)
>>> print a
12
>>>=20

But don't blame me if you don't understand your own programs three months
from now... <wink>

I suggest you read
http://www.crosswinds.net/~agauld/
http://www.ibiblio.org/obp/thinkCSpy/
http://www.python.org/doc/current/tut/

Especially the parts about functions, modules, classes and object oriented
programming.

HTH,
  Kalle
--=20
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD

--Dxnq1zWXvFF0Q93v
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE6ebA4dNeA1787sd0RAhDcAKCSRsGjb4wy5SxHxbU/bxw4lnyedQCgybTz
UTMtlqPmdF7dsKRe2TDy6Rg=
=Sj6q
-----END PGP SIGNATURE-----

--Dxnq1zWXvFF0Q93v--