canyon289
canyon289

Reputation: 3505

If not x % y: Do something

I have a question about the following statement in Python

if not x % y: 
    # do something

After seeing this in a piece of code and experimenting I found that if modulo evaluates to anything but zero it'll skip the "do something" code.

My question is, is there a general rule about If and If not statements with implied conditions and are there any good references for Python "tricks" like this?

I apologize about the broad question but this threw me for a loop when I first saw it. I would like to learn as many of these short hand tricks as I can!

Upvotes: 2

Views: 1461

Answers (3)

kindall
kindall

Reputation: 184280

  • None is false.
  • Numbers that are not zero are considered true; 0 is false
  • Strings with any content are true; "" is false
  • Containers with anything in them are true; [], (), and {} (and other empty containers) are false

This can be overridden on your own types by defining __len__() or __nonzero__() (the latter is named __bool__() in Python 3). You could even define, for example, a zero that evaluates as true:

class trueint(int):
    def __nonzero__(self):
        return True
    __bool__ = __nonzero__    # Python 3

truezero = trueint(0)

if truezero:
    print("yep, this zero is true!")

You probably shouldn't do this, as it will confuse Python programmers, but you could.

Upvotes: 5

voscausa
voscausa

Reputation: 11706

This behaviour is called Truthiness in Python: http://www.udacity.com/wiki/CS258%20Truthiness%20in%20Python

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

There is no such thing as an "implied condition" in Python; there are true values, and there are false values.

These are false:

  • None
  • 0 (or any number equal to it)
  • Empty sequences ('', u'', b'', [], ()), mappings ({}), or sets ({,})
  • Objects that return false from their __nonzero__() method

Anything else should be considered true until proven otherwise.

Upvotes: 2

Related Questions