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.
Truthy values are values that evaluate to True in a boolean context. Falsy values are values that evaluate to False in a boolean context. Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None , and False .
We can use any object to test the truth value. By providing the condition in the if or while statement, the checking can be done. Until a class method __bool__() returns False or __len__() method returns 0, we can consider the truth value of that object is True.
Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With