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

前端 未结 6 1519
广开言路
广开言路 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: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.

提交回复
热议问题