22
if <boolean> :
   # do this

boolean has to be either True or False.

then why

if "poi":
   print "yes"

output: yes

i didn't get why yes is printing , since "poi" is nether True or False.

cs95
  • 379,657
  • 97
  • 704
  • 746
navyad
  • 3,752
  • 7
  • 47
  • 88
  • Related: [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/q/39983695/4518341) – wjandrea Jul 05 '20 at 01:36

4 Answers4

37

Python will do its best to evaluate the "truthiness" of an expression when a boolean value is needed from that expression.

The rule for strings is that an empty string is considered False, a non-empty string is considered True. The same rule is imposed on other containers, so an empty dictionary or list is considered False, a dictionary or list with one or more entries is considered True.

The None object is also considered false.

A numerical value of 0 is considered false (although a string value of '0' is considered true).

All other expressions are considered True.

Details (including how user-defined types can specify truthiness) can be found here: http://docs.python.org/release/2.5.2/lib/truth.html.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
  • 1
    I believe Python will always test __len__() of any class that has one, and consider a result of 0 to mean the object evaluates to `false` in a boolean context. This is pretty close to the same thing as imposing the same rule even on user-defined classes (you'd have to deliberately return some non-intuitive value from your __len__() method, or leave it out entirely, to avoid following the same rule as built-ins). – Larry Lustig Aug 28 '13 at 15:26
  • 2
    For anyone reading the above answer : make sure you actually read the doc (either the above link or here : http://docs.python.org/2/reference/datamodel.html#object.__nonzero__) – bruno desthuilliers Aug 28 '13 at 15:26
  • 3
    Equivalent documentation for Python 3: http://docs.python.org/3/reference/datamodel.html#object.__bool__ – LexyStardust Aug 28 '13 at 15:51
  • 1
    Just in case anyone is confused by something like `'a' or 'b'` returning `'a'` instead of `True`, note that `and` and `or` are "short circuit operators", and "When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument." Since `'a'` evaluates as `True`, the whole expression must be true, and so the truth value of `'b'` is not even evaluated. https://docs.python.org/3.6/tutorial/datastructures.html#more-on-conditions – Paul de Barros Feb 20 '17 at 00:40
11

In python, any string except an empty string defaults to True

ie,

if "MyString":
    # this will print foo
    print("foo")

if "":
    # this will NOT print foo
    print("foo")
Cameron Sparr
  • 3,925
  • 2
  • 22
  • 31
  • same is true for list and other data types, isn't it ? – navyad Aug 28 '13 at 15:17
  • 4
    "defaults to `True`" is not really correct. How about "evaluates to `True` in a Boolean context"? – Tim Pietzcker Aug 28 '13 at 15:20
  • naveen yadav, yes, it is true for all built-in collection types. Empty collections are False, non-empty collections are True. A string is a sequence, which is a type of collection. – Hammerite Aug 28 '13 at 15:21
10

What is happening here is Python' supplement of implicit bool() constructor after the if, Because anything followed by if should be resolved to be boolean. In this context your code is equivalent to

if bool("hello"):
   print "yes"

According to Python bool(x) constructor accepts anything and decides the truthiness based on below cases

  • If x is integer, Only 0 is False everything else is True
  • If x is float, Only 0.0 is False everything else is True`
  • If x is list, Only [] is False everything else is True
  • If x is set/dict, Only {} is False everything else is True
  • If x is tuple, Only () is False everything else is True
  • If x is string, Only “" is False everything else is True. Be aware that bool(“False”) will return to True

Here is the log for the cases I listed above

Python 3.4.3 (default, Feb 25 2015, 21:28:45) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bool(0)
False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(0.0)
False
>>> bool(0.02)
True
>>> bool(-0.10)
True
>>> bool([])
False
>>> bool([1,2])
True
>>> bool(())
False
>>> bool(("Hello","World"))
True
>>> bool({})
False
>>> bool({1,2,3})
True
>>> bool({1:"One", 2:"Two"})
True
>>> bool("")
False
>>> bool("Hello")
True
>>> bool("False")
True
nehem
  • 12,775
  • 6
  • 58
  • 84
0

In most programming languages, a non-empty string is considered "truthy," which means it is treated as equivalent to True in a boolean context. This is why in your example:

if "poi":
  print("yes")

In this code the poi is considered as true and hence, the output is 'yes'

In Boolean contexts, values like 0, False, None, and empty strings "" are considered "falsy," meaning they are treated as equivalent to False.

Even if 'poi' is different from 'true' it's still considered as a true in the Boolean context.

If you really want to do real coding, then you will need to replace the poi by true.

if True:
  print("yes")

This will also give you the result as 'yes'.