[Tutor] text editor problems

D-Man dsh8290@rit.edu
Sun, 21 Jan 2001 21:40:12 -0500


On Sat, Jan 20, 2001 at 03:45:27PM -0800, Matthias Hager wrote:
| That's what I thought(just see if those variables are there), I have(kind of, just reworded for less space)
| 
| 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.
| 
| I know you guys gotta be getting sick of me, but what am I doing wrong?

If we were getting sick of you we would unsubscribe.  We subscribed to
the list to help.  :-)

| I can't figure it out, and I've tried changing it to:
| if oname != "":
| elif sname != "":
| 
| All kinds of stuff, but I'm still getting an error.
| 

The exact error is "NameError".  That is, the name (variable) doesn't
exist.  Have you ever used a statically typed language like C, C++,
Java, or Eiffel?  In each of those languages you must declare all
variables before you can use them.  ie:

int i ;
i = 3 ;
if j == 4 :
	print "i is 4"

Oops.  I used "j", but I didn't declare it.  The compiler will then
say something like "no identifier 'j' found in local namesapce".  I
haven't declared j, so it doesn't exist.


Python is a bit different.  You don't declare variables, but instead
create them through the "assignment" operation.  (I put it in quotes
because it has more to do with name bindins than assignment, but that
is a detail)  If I write the following python code, I am ok:

i = 3 
if i == 4 :
	print "i is 4"
else :
	print "i isn't 4"

but if I make a typo and write:

j = 3
if i == 4 :
	print "i is 4"

I will get a NameError because the name 'i' isn't defined.



You tried checking for sname == "", but since sname hadn't been
assigned to it doesn't exist yet.  (I think Perl implicitly gives all names the
value 'undefined' which compares equal to "", the empty string)

To solve your problem, somewhere during progam initialization set
sname equal to "".  I would prefer setting it to None since that
better reflects your intent (and you don't have any static typing
restrictions).  If you do this, the variable sname will exist when the
function is called and you won't get any NameError's.  Then in the
function check to see that sname has been set to something useful,
rather than None.  (I haven't tried, but I bet you will get an
exception if you try to call open() with None as the filename
argument).

| Any help is appreciated
| 
| Matthias
| 

HTH,
-D

| 
| 
| --
| Programming isn't cool, it's awesome.
|