'True' and 'False' in Python

后端 未结 3 873
忘掉有多难
忘掉有多难 2020-12-07 16:13

I tried running this piece of code:

path = \'/bla/bla/bla\'

if path is True:
    print \"True\"
else:
    print \"False\"

And it prints

3条回答
  •  时光取名叫无心
    2020-12-07 17:10

    While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

    I thought Python treats anything with value as True. Why is this happening?

    Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

    if 0:
        print("Won't get here")
    

    This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

    from decimal import *
    from fractions import *
    
    if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
        print("Won't get here")
    

    Here are the other value which evaluate to False:

    if None or False or '' or () or [] or {} or set() or range(0):
        print("Won't get here")
    

    Sources:

    1. Python Truth Value Testing is Awesome
    2. Truth Value Testing (in Built-in Types)

提交回复
热议问题