Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these loops not executed?

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

like image 920
Ovi Avatar asked Nov 23 '25 10:11

Ovi


1 Answers

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'
like image 62
That1Guy Avatar answered Nov 24 '25 23:11

That1Guy