[Tutor] Returned values

Daniel Ehrenberg littledanehren at yahoo.com
Sat Dec 20 14:47:15 EST 2003


Ryan Sheehy wrote:
> Hi Daniel,
> 
> Thanks for your reply.
> 
> It's just that I was wondering if there would ever
> be a case where I would
> type something in like so using xyz's output like so
> ...
> 
> abc = 1
> if xyz(abc) == 1:
>  ...etc
> 
> ... now if xyz's output was boolean or a string (or
> anything other than what
> I may have been expecting - i.e. 1) what would
> happen?
> 
> This then brings me back to my original question -
> how would I know what the
> function returns so that I can create a proper
> conditional statement with
> it.
> 
> Thanks heaps,
> 
> 
> Ryan

Generally, things must be of the same type to return
True for an equality test. However, as I stated
before, the distinction between integers and floats is
weak, so  if you test 1 == 1.0, it will return True.
Here are some equality examples.
>>> 1==1L
True
>>> [1, 2] == (1, 2)
False
>>> u'a' == 'a' #u'a' is unicode
True
>>> 1, 2 == (1, 2) #comma has higher precedence than
==
(1, True)
>>> '1' == 1
False
>>> [1] == 1
False
>>> (1,) == 1
False
>>> ['1', '2'] == '12'
False

I hope you can figure what's happening there; Python's
system for testing equality is fairly complicated. The
equality system in Python is less strict than in most
other languages (like C) but less strict than in
weakly-typed languages (like Visual Basic). There is a
different operator called 'is' to test out if things
are exactly the same (by checking their ids), but it
requires that things must be the same instance of
stuff. For example, [1, 2] is [1, 2] would return
False, but x = [1, 2] ; y = x ; x is y would return
True because x and y are refering to the same thing.
It all has to do with Python's linking model for
variables; it's very complicated. Here are some
examples of the usage of is:

>>> 1 is 1
True
>>> [1] is [1]
False
>>> def test(): pass
...
>>> test() is None #this is an idiom; if a function
doesn't return anything, it returns None
True
>>> 'a' is 'a'
True
>>> u'a' is 'a'
False
>>> (1,) is (1,)
False
>>> 1 is 1.0
False
>>> 1 is 1L
False

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/



More information about the Tutor mailing list