I am experimenting with booleans to get a better understanding of them. My book says that any empty type of data is interpreted as "False", and any non-empty type of data is interpreted as "True". When I wrote the following program, I thought I would get an infinite loop, but the program returned nothing.
def main():
while False == "":
print("i")
main()
I also tried
def main():
while True == "b":
print("i")
main()
I also expected this to be an infinite loop, but it returned nothing
True is a boolean, "b" is a string. They are not equal.
However, "b" is "truthy"
>>>bool("b")
True
This is why you can do the following if you desire an infinite loop:
while "my not empty string that is truthy":
do.something()
# This is the same as:
while True:
do.something()
You can also take advantage of the name's "truthiness" in if-statements:
if "b": # "b" is 'truthy'
print 'this will be printed'
if "": # "" is not 'truthy'
print 'this will not be printed'
This is true for other types as well:
if ['non-empty', 'list']: # Truthy
if []: # Falsey
if {'not' : 'empty dict'}: # Truthy
if {}: # Falsey
Be careful with integers. Boolean subclasses int. 0 is not truthy:
if 1:
print 'this will print'
if 0:
print 'this will not print'
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