0

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

Edited by shanenin

3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by Gribouillis
0

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. :)

0

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.

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.