namespace issue?

Christopher A. Craig com-nospam at ccraig.org
Fri Jun 22 08:05:44 EDT 2001


Michael Powe <looie+gnus at aracnet.com> writes:

> Actually, it doesn't contain the dash.  The dash is only inserted if I
> press the enter key, leaving the PN string empty.  In the case of an

I see that now.  I was really only paying attention to the
conditional...

> So now the question is, 'why'?  Am I misusing the string.find()
> function? Okay, string.find() returns -1 when the string is not found,
> which would seem to be what I expected, a false result.  Maybe python
> doesn't treat -1 as false?  Well, I'll try being explicit and testing
> for -1 return.  I probably have just confused myself hopelessly.

As others have pointed out, -1 is not false in Python.  I would highly
recommend you (and anyone else just learning the language) read
section 2 (Built-in types) of the Library reference thoroughly.  There
is a lot of very useful information on how builtin types and functions
work in there.

More importantly though your code (which I quote below for
readability), does not initialize Ph if the conditional is false.
Even if you fix the logic error in the code, you are left with
something that possibly returns an uninitialized value, which is bad
practice.  I presume that you want the program to return a value even
when that condition is false, so you should have an else clause.  If
you want an error condition to occur when the condition is false then
you should assert() the condition.

--- Your code (fixed) ---
>>> def GetNum2():	
... 	AC = raw_input("Area Code: ")
... 	PN = raw_input("Phone Number: ")
...	if not PN : PN = '000-0000'
...	if not AC : AC = '503'
...	if len(PN) < 8 and string.find(PN,'-')==-1:
...		Ph = PN[:3] + '-' + PN[3:]
...	return Ph
... 
--- end your code ---

--- better ---
>>> def GetNum3():	
... 	AC = raw_input("Area Code: ")
... 	PN = raw_input("Phone Number: ")
...	if not PN : PN = '000-0000'
...	if not AC : AC = '503'
...	if len(PN) < 8 and string.find(PN,'-')==-1:
...		Ph = PN[:3] + '-' + PN[3:]
...     else
...             Ph = PN
...	return Ph
... 
--- end better ---

--- assert ---
>>> def GetNum4():	
... 	AC = raw_input("Area Code: ")
... 	PN = raw_input("Phone Number: ")
...	if not PN : PN = '000-0000'
...	if not AC : AC = '503'
...     assert(len(PN)<8 and string.find(PN,'-')==-1)
...	return PN[:3] + '-' + PN[3:]
--- end assert ---




-- 
Christopher A. Craig <com-nospam at ccraig.org>
"Only two things are infinite, the universe and human stupidity, and I'm not
sure about the former." Albert Einstein



More information about the Python-list mailing list