Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why 'and not' gets executed in this if statement?

From my understanding, and is a short-circuit operator as explained in the doc. But, why the part c gets printed every I run the code below?

My solution: if ('RB' in t) and (not ',' in t): ..., but what I want is an explanation.

test = '977'

if 'RB' and '+' in test:
    print('a')
    test = int(test.replace('RB+', '')) * 1000
elif ',' and 'RB' in test:
    print('b')
    temp_test = test.replace(',', '')
    test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' and not ',' in test:
    print('c')
    test = int(test.replace('RB', '')) * 1000
else:
    test = int(test)

print(test)

Ouput

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

c
977000

>Solution :

Because you are effectively checking the ‘truthiness’ of the string ‘RB, which is True. See:
https://stackoverflow.com/questions/18491777/truth-value-of-a-string-in-python#:~:text=3%20Answers&text=Python%20will%20do%20its%20best,empty%20string%20is%20considered%20True%20.

Your third elif breaks down as:

elif ('RB') and (not ',' in test'):

You probably want:


if 'RB' in test and '+' in test:
    print('a')
    test = int(test.replace('RB+', '')) * 1000
elif ',' in test and 'RB' in test:
    print('b')
    temp_test = test.replace(',', '')
    test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' in test and not ',' in test:
    print('c')
    test = int(test.replace('RB', '')) * 1000
else:
    test = int(test)

print(test)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading