I am just back messing around a bit with programming. I am trying to clear out the mental cobwebs. I thought any non empty string evaluates to True. but according to my code, it does not apear so

word = 'abc'
if word is True:
    print 'yes'

else:
    print 'no'

this gives me 'no' for output. I would think it should give me 'yes'. What am I doihg wrong

Recommended Answers

All 3 Replies

The is keyword tests for identity (http://docs.python.org/release/2.3.5/ref/comparisons.html). So it's true when both sides point the same memory location.

Your thought is correct though; non-empty strings equal true. To test it, you could write code like so:

word = 'abc'
if word:
    print 'yes'
else:
    print 'no'

That code's not tested by the by.. but it should work. :)

thanks for clearing that up :-)

In a test, a value is converted to a boolean using it __nonzero__ method (in python 3 it's __bool__). Here is an example

>>> class A(object):
...  def __nonzero__(self):
...   print("__nonzero__() called")
...   return True
... 
>>> a = A()
>>> if a:
...  print("success")
... 
__nonzero__() called
success
>>> bool(a)
__nonzero__() called
True

The same method is called if the instance is converted with the bool() function. You could write if bool(word) is True as an alternative.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.