In Python how should I test if a variable is None, True or False

前端 未结 6 1107
野的像风
野的像风 2020-11-30 20:16

I have a function that can return one of three things:

  • success (True)
  • failure (False)
  • error reading/parsing stream
6条回答
  •  借酒劲吻你
    2020-11-30 21:06

    There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.

    a = 0 
    b = 10 
    c = None
    
    ### Common approach that can cause a problem
    
    if not a:
        print(f"Answer is not found. Answer is {str(a)}.") 
    else:
        print(f"Answer is: {str(a)}.")
    
    if not b:
        print(f"Answer is not found. Answer is {str(b)}.") 
    else:
        print(f"Answer is: {str(b)}")
    
    if not c:
        print(f"Answer is not found. Answer is {str(c)}.") 
    else:
        print(f"Answer is: {str(c)}.")
    
    Answer is not found. Answer is 0.   
    Answer is: 10.   
    Answer is not found. Answer is None.
    
    ### Safer approach 
    if a is None:
        print(f"Answer is not found. Answer is {str(a)}.") 
    else:
        print(f"Answer is: {str(a)}.")
    
    if b is None:
        print(f"Answer is not found. Answer is {str(b)}.") 
    else:
        print(f"Answer is: {str(b)}.")
    
    if c is None:
        print(f"Answer is not found. Answer is {str(c)}.") 
    else:
        print(f"Answer is: {str(c)}.")
    
    
    Answer is: 0.
    Answer is: 10.
    Answer is not found. Answer is None.
    

提交回复
热议问题