[Tutor] Re: [Turor] text editor problems

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 22 Jan 2001 11:50:28 -0800 (PST)


On Sun, 21 Jan 2001, wheelege wrote:

> > def save():
> >   if sname:
> >     open sname and write to it
> >   elif oname:
> >     open oname and write to it
> >   else:
> >     saveas()
> >
> > def saveas():
> >   sname = asksaveasfile
> >   blah blah
> >
> > def open():
> >   oname = askopenfile
> >   blahblah
> >
> > Then it gives me the error: No variable named sname exists.


It helps to know that Python's rules for handling variables is different
from Perl's:  in Perl, your variables are global by default, and you get
"local" variables by putting something like:

    my $foobar = 10;

However, in Python, all your variables in function are "my" variables, so
the rule is backwards.  We expect to use more local than global variables,
so Python makes globals a special case, where you have to say "global":

    global sname = saveasfile

or

    global oname = askopenfile


That being said, Pythonic style tries to avoid global variables whenever
possible, so expect some resistance from us when you ask for a straight,
direct translation.

Hope that clears things up!