Python Booleans

Why in Python integers and floats, without evaluation in a boolean context, is equivalent to True? Other data types must be evaluated using the operator or bool ().

+4
source share
4 answers

This is not True :

 >>> print("True" if 1 else "False") True >>> print("True" if 0 else "False") False >>> print("True" if 0.0 else "False") False >>> print("True" if 123.456 else "False") True >>> print("True" if "hello" else "False") True >>> print("True" if "" else "False") False >>> print("True" if [1,2,3] else "False") True >>> print("True" if [] else "False") False >>> print("True" if [[]] else "False") True 

Only nonzero numbers (or non-empty sequences / container types) are evaluated to True .

+6
source

Here is a usage example -

 >>> bool(2) True >>> bool(-3.1) True >>> bool(0) False >>> bool(0.0) False >>> bool(None) False >>> bool('') False >>> bool('0') True >>> bool('False') True >>> bool([]) False >>> bool([0]) True 

In Python, this is False -

  • Boolean False
  • Any numeric value equal to 0 (0, 0.0, but not 2 or -3.1)
  • Special Meaning None
  • Any empty sequence or collection, including an empty string ( '' , but not '0' or 'hi' or 'False' )) and an empty list ( [] , but not [1,2, 3] or [0] )

The rest will be evaluated to True . More details .

+4
source

From the Python 5.1 documentation:

Any object can be checked for true, for use in an if or while condition, or as an operand of the following Boolean operations. The following values ​​are considered false:

  • None
  • False
  • zero of any number type, for example, 0 , 0L , 0.0 , 0j .
  • any empty sequence, for example '' , () , [] .
  • any empty mapping, for example {} .
  • instances of user-defined classes if the class defines the __nonzero__() or __len__() method when this method returns the integer 0 or the value bool False.

Why? Because it is convenient when iterating through objects, looping, checking if a value is empty, etc. In general, it adds some parameters to how you write code.

+4
source

0 evaluates to False.

 if 0: assert(0) 
0
source

Source: https://habr.com/ru/post/1479869/


All Articles