Python And Or statements acting ..weird

前端 未结 5 1361
盖世英雄少女心
盖世英雄少女心 2020-12-07 04:30

I have this simple line of code:

i = \" \"

if i != \"\" or i != \" \":
    print(\"Something\")

This should be simple, if i is not empty <

相关标签:
5条回答
  • 2020-12-07 05:07

    Your print statement will always happen, because your logic statement is always going to be True.
    if A or B:
    will be True if either A is True OR B is True OR both are True. Because of the way you've written the statement, one of the two will always be True. More precisely, with your statement as written, the if statement correlates to if True or False: which simplifies to if True:.
    It seems that you want an and statement instead of an or.

    0 讨论(0)
  • 2020-12-07 05:14

    This condition:

    if i != "" or i != " ":
    

    will always be true. You probably want and instead of or...

    0 讨论(0)
  • 2020-12-07 05:15

    De Morgan's laws,

    "not (A and B)" is the same as "(not A) or (not B)"
    
    also,
    
    "not (A or B)" is the same as "(not A) and (not B)".
    

    In your case, as per the first statement, you have effectively written

    if not (i == "" and i == " "):
    

    which is not possible to occur. So whatever may be the input, (i == "" and i == " ") will always return False and negating it will give True always.


    Instead, you should have written it like this

    if i != "" and i != " ":
    

    or as per the quoted second statement from the De Morgan's law,

    if not (i == "" or i == " "):
    
    0 讨论(0)
  • 2020-12-07 05:23

    I will explain how or works.
    If checks the first condition and if it is true it does not even check for the second condition.
    If the first condition is false only then it checks for second condition and if it is true the whole thing becomes true.
    Because

    A B Result  
    0 0   0  
    0 1   1  
    1 0   1  
    1 1   1  
    

    So If you want to satisfy both condition of not empty and space use and

    0 讨论(0)
  • 2020-12-07 05:23
    i = " "
    

    you have the condition as

    if i != "" or i != " ":
    

    here i != "" will evaluate to True and i != " " will evaluate to False

    so you will have True or False = True

    you can refer this truth table for OR here

    True  or False = True
    False or True  = True
    True  or True  = True
    False or False = False
    
    0 讨论(0)
提交回复
热议问题