What is Truthy and Falsy? How is it different from True and False?

前端 未结 6 1517
广开言路
广开言路 2020-11-21 04:16

I just learned there are truthy and falsy values in python which are different from the normal True and False.

相关标签:
6条回答
  • 2020-11-21 05:06

    All values are considered "truthy" except for the following, which are "falsy":

    • None
    • False
    • 0
    • 0.0
    • 0j
    • Decimal(0)
    • Fraction(0, 1)
    • [] - an empty list
    • {} - an empty dict
    • () - an empty tuple
    • '' - an empty str
    • b'' - an empty bytes
    • set() - an empty set
    • an empty range, like range(0)
    • objects for which
      • obj.__bool__() returns False
      • obj.__len__() returns 0

    A "truthy" value will satisfy the check performed by if or while statements. We use "truthy" and "falsy" to differentiate from the bool values True and False.

    Truth Value Testing

    0 讨论(0)
  • 2020-11-21 05:10

    Where should you use Truthy or Falsy values ? These are syntactic sugar, so you can always avoid them, but using them can make your code more readable and make you more efficient. Moreover, you will find them in many code examples, whether in python or not, because it is considered good practice.

    As mentioned in the other answers, you can use them in if tests and while loops. Here are two other examples in python 3 with default values combined with or, s being a string variable. You will extend to similar situations as well.

    Without truthy

    if len(s) > 0:
        print(s)
    else:
        print('Default value')
    

    with truthy it is more concise:

    print(s or 'Default value')
    

    In python 3.8, we can take advantage of the assignment expression :=

    without truthy

    if len(s) == 0:
        s = 'Default value'
    do_something(s)
    

    with truthy it is shorter too

    s or (s := 'Default value')
    do_something(s)
    

    or even shorter,

    do_something(s or (s := 'Default value'))
    

    Without the assignment expression, one can do

    s = s or 'Default value'
    do_something(s)
    

    but not shorter. Some people find the s =... line unsatisfactory because it corresponds to

    if len(s)>0:
        s = s # HERE is an extra useless assignment
    else:
        s = "Default value"
    

    nevertheless you can adhere to this coding style if you feel comfortable with it.

    0 讨论(0)
  • 2020-11-21 05:11

    Python determines the truthiness by applying bool() to the type, which returns True or False which is used in an expression like if or while.

    Here is an example for a custom class Vector2dand it's instance returning False when the magnitude (lenght of a vector) is 0, otherwise True.

    import math
    class Vector2d(object):
        def __init__(self, x, y):
            self.x = float(x)
            self.y = float(y)
    
        def __abs__(self):
            return math.hypot(self.x, self.y)
    
        def __bool__(self):
            return bool(abs(self))
    
    a = Vector2d(0,0)
    print(bool(a))        #False
    b = Vector2d(10,0)    
    print(bool(b))        #True
    

    Note: If we wouldn't have defined __bool__ it would always return True, as instances of a user-defined class are considered truthy by default.

    Example from the book: "Fluent in Python, clear, concise and effective programming"

    0 讨论(0)
  • 2020-11-21 05:13

    Truthy values refer to the objects used in a boolean context and not so much the boolean value that returns true or false.Take these as an example:

    >>> bool([])
    False
    >>> bool([1])
    True
    >>> bool('')
    False
    >>> bool('hello')
    True
    
    0 讨论(0)
  • 2020-11-21 05:16

    As the comments described, it just refers to values which are evaluated to True or False.

    For instance, to see if a list is not empty, instead of checking like this:

    if len(my_list) != 0:
       print("Not empty!")
    

    You can simply do this:

    if my_list:
       print("Not empty!")
    

    This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.

    Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.

    The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like those described above, and those which are considered False.

    For example, an empty list ([]) is considered "falsy", and a non-empty list (for example, [1]) is considered "truthy".

    See also this section of the documentation.

    0 讨论(0)
  • 2020-11-21 05:22

    Falsy means something empty like empty list,tuple, as any datatype having empty values or None. Truthy means : Except are Truthy

    0 讨论(0)
提交回复
热议问题