Learning Python

8. Booleans

8.1. The basics about booleans

#!/usr/bin/env python3

def main():
    print(1 > 2)
    print(1 == 2)
    print(1 < 2)
    print(bool(0))
    print(bool(1))


if __name__ == "__main__":
    main()

Output:

False
False
True
False
True
#!/usr/bin/env python3

def main():
    x = 10
    y = 5

    if x > y:
        print("x is greater than y")
    else:
        print("x is not greater than y")


if __name__ == "__main__":
    main()

Output:

x is greater than y

8.2. Some values are false

#!/usr/bin/env python3

class myClass():
    def __len__(self):
        return 0


def main():
    myobj = myClass()
    print(bool(myobj))


if __name__ == "__main__":
    main()

Output:

False

8.3. Functions can also return a boolean

#!/usr/bin/env python3

def trueFunction():
    return True


def main():
    if trueFunction():
        print("True")
    else:
        print("False")


if __name__ == "__main__":
    main()

Output:

True