What does it mean to say "if n"?

Viewed 2714

What does it mean to say if n? I don't get why if n works in an if statement. Shouldn't there be an argument such as if n == 0 or something, not just if n?

def AddMusicAtPosition(self, newMusic, n):
    if n:
        self.nextMusic.AddMusicAtPosition(newMusic, n - 1)
    else:
        newMusic.nextMusic = self.nextMusic
        self.nextMusic = newMusic
4 Answers

In Python, if n is equivalent to if bool(n).

For integers, bool(i) equals to i != 0.


If n is an instance of a class, then

  • if the class defines __bool__, then n.__bool__() is called
  • if the class doesn't define __bool__ but __len__, then n.__len__() != 0 is evaluated
  • if the class defines neither __bool__ nor __len__, it always evaluates to True (think like n is not None).

Usually conditions are like:

if n==1:

But that evaluates to:

if True:

If the conditions is right, python in default everything is True, so the statement is passed, and since:

bool(n)

Could be True or False too, n could do it already, and the code will pass if n is True, don't pass if n is False, so that's why it works.

Any value in Python can be tested for truth. As long as it's not None, False, zero, or empty; it is considered true. See more details in the documentation.

In your case the recursion should stop when n gets to zero as zero is not considered True. You can test this with:

if 0:
  print('zero is true') # won't be printed
else:
  print('zero is false') # will be printed

In Python, almost everything is True except False, None, 0 and Empty entities (string, list, sets, dictionary)!(Could have miss others)

So if you state that:

if n:
    print(True)

If n is not 0, False, None or Empty entities, then it would print True.

To test the values and behavior, you can do:

ns = [None, 0, False, '', {},(), [],1, True,]

for n in ns:
    if n:
        print(n, 'It is True')
    else:
        print(n, 'it is False')

So what happens is that if n, checks for truthfulness of value n :)

Related