Search code examples
pythonif-statementnested-if

Nested if vs. if statement with two conditions behaves differently:


I have a dictionary my_dict1, which contains a key 'Error' I also have another dictionary my_dict2 that either has multiple keys, or is empty. I want to have an if statement that checks whether my_dict1['Error'] is False and check if my_dict2 has any content in it. The code is as follows:

my_dict1 = {'Error': False}
my_dict2 = {'somekey': True}

if my_dict1['Error'] == False:
    if len(my_dict2) > 0:
        print('ok')
else:
    print('no')

This code results in 'ok' as expected.

if my_dict1['Error'] == False & len(my_dict2)> 0:
    print('ok')
else:
    print('no')

This results in 'no'. Am I understanding the & statement wrong?


Solution

  • The error originates from the precedence of the operators. Your expression is equivalent to:

    my_dict1['Error'] == (False & len(my_dict2)) > 0

    Now since False & 1 will result in 0, since False acts as 0, and the bitwise and-ing of 0 and 1 is 0.

    The expression my_dict['Error'] == 0 > 0 is False. The my_dict['Error'] == 0 will succeed, but 0 > 0 is of course False.

    If you want to check two conditions, you should use the and operator, like:

    if my_dict1['Error'] == False and len(my_dict2) > 0:
        print('ok')
    else:
        print('no')

    or more Pythonic:

    if not my_dict1['Error'] and my_dict2:
        print('ok')
    else:
        print('no')

    The two are not entirely the same since not my_dict['Error'] will succeed, given the truthiness of the corresponding value is True. If the items map on bools, then the two are equivalent.