Digging deeper into python if statements

Question:

It might be a really silly question, but I was not able to find the answer to it anywhere else, I’ve looked at SO, but there is nothing I could find related to my question.

Question:

In python, don’t know about other languages, whenever we call if statements for a builtin class it returns something which the if statement interprets, For example,

a = 0
if a: print("Hello World")

The above statement does not print anything as the if a is False. Now which method returned that it is False, or is there a method the if statement calls in order to know it ??

Or more precisely, how does the if statement work in python in a deeper level ?

Asked By: basic mojo

||

Answers:

Good question! This is not to do with the if statement. Instead, it is the object itself.

If an object defines the builtin method __bool__, it can decide whether it is "truthy" or "falsey" (aka whether to return true or false).

See this answer for more details, or the official Python docs

Here is a quick example of a Dog class which is False if it has no name:

class Dog:
    def __init__(self, name):
        this.name = name

    def __bool__(self):
        return this.name != ""

dog1 = Dog("")
dog2 = Dog("Foo")
if (dog1): print("dog1")
if (dog2): print("dog2")
> dog2
Answered By: dantechguy

Objects have __bool__ methods that are called when an object needs to be treated as a boolean value. You can see that with a simple test:

class Test:
    def __bool__(self):
        print("Bool called")
        return False

t = Test()
if t:   # Prints "Bool Called"
    pass

bool(0) gives False, so 0 is considered to be a "falsey" value.

A class can also be considered to be truthy or falsey based on it’s reported length as well:

class Test:
    def __len__(self):
        print("Len called")
        return 0

t = Test()
if t:
    pass
Answered By: Carcigenicate

In Python, booleans (result of an if-else condition) is often interpreted as integers 0 and 1. 0 being False and 1 being True.

In you case since, you assigned value of a to be 0, which python interpreted as False, hence it didn’t print anything.

A simple rule in Python is and empty container (list, dict, set, tuple, str) or None or Number (int/float) which is 0 would be considered as False. Any number greater than 0 or 0.0000 so on would be considered True.

Answered By: XAMES3
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.