Change language

Using objects instead of True and False – truthy and falsy values in Python

| |

Values instead of boolean variables

Python, like other languages, has a boolean variable type called bool, which has only two values: True and False. This is what is returned by logical statements (such as comparing numbers or checking if an item is in a list), and this is the type usually used in if and while statements. However, it is not necessary to use bool or operators explicitly: there are rules that convert any type to True or False.

Featured review: Best laptop for engineering student

Here is how it works:

>>> a = 5

>>> if a:
    print(a)
# Print
5

>>> a = 0

>>> if a:
    print(a)

# Nothing

Boolean context

Any value in Python can be interpreted as True or False according to the rules of the language. This is also written about in the documentation:

Any object can be tested for truth and used in if and while conditions and as an operand of boolean operations (and, or, not).

If an object is used in this way, it is in a boolean context. Roughly speaking, this is a place in code that requires the object to be either True or False.

Both a variable and an expression can be used in a boolean context. If an expression is used, then the truth of its result is evaluated.

Objects that equate to False

Any object for which the len method is defined that returns 0 for that object is falsy. Documentation:

By default, an object is considered true if its class does not define a bool method that returns False for the object, or a len method that returns zero for it.

Sequences and collections

  • empty list: [];
  • empty tuple: ();
  • empty dictionary: {};
  • empty set: set();
  • empty string: "";
  • empty range: range(0).
  • Zeros of any numeric types
  • integer zero: 0;
  • floating point zero: 0.0;
  • complex zero: 0j.
  • Constants
  • None;
  • False.

Objects that equate to True

According to the documentation:

By default, any object has a true value.

In particular, true objects are:

  • all non-empty sequences and collections (lists, tuples, dictionaries, sets, ranges, and strings);
  • All non-zero numbers;
  • True.


Function bool()

You can use this function to test whether any value is true or false. According to the documentation it:

Returns a Boolean value, i.e., either True or False. The argument x is converted using the standard truth check procedure.

For example:

>> bool(5)
True
>>> bool(0)
False

You can pass both the value and the variable containing it to this function.

Why do I need it?

The advantage of true and false values is that they allow you to make the code concise and understandable. Here are two examples:

Example 1, with an error message

def print_even(data):
  if len(data) > 0:
    for value in data:
      if value % 2 == 0:
        print(value)
   else:
     print("Empty list in argument")

Example 2, with an exception

>>> def print_even(data):

  if not data:
    raise ValueError("The argument data cannot be empty")

  for value in data:
    if value % 2 == 0:
      print(value)

True and false values of arbitrary objects

If you want your objects to have more than just true values, you can add an bool() method to the class and define rules to determine if the object is true or false.

For example, we have a class like this:

>>> class Account:

  def __init__(self, balance):
    self.balance = balance

Since it has no special methods, all objects of this class have true values:

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
True

This can be fixed by adding bool():

>>> class Account:
  def __init__(self, balance):
    self.balance = balance

  def __bool__(self):
    return self.balance > 0

Now the object has a true value as long as the balance is greater than zero. If the balance is zero or negative, the value will be false.

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
False

If the class has no bool() method, but has len() method, then the truth of the object is determined by the truth of what len() returns.

Featured review: Best laptop for Machine Learning

This is how the mechanism works that allows you to use any object as a boolean object. With it you can make code easier and clearer; just don't forget to name variables meaningfully - some pabotat() if cnucok_2 else He_pabotat() is useless with or without Boolean context.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically