How to use Boolean operators in an If statement in Python

Question:

I just read a tutorial on Boolean operators in Python, but I can’t get my head around how I can use an if statement together with and.

For example, this doesn’t seem to work well:

# variable1 = 'lorem'
variable2 = 'ipsum'

if 'variable1' and 'variable2' in locals():
    print('Both exist')
else:
    print('Only variable:', variable1, 'exist')

It gives me Both exist when in fact only one variable exist.

So instead of a boolean approach, I tried using multiple if loops like this:

# variable1 = 'lorem'
variable2 = 'ipsum'

if 'variable1' in locals():
    if 'variable2' in locals():
        print('Both exist')
else:
    print('Only variable:', variable1, 'exist')

But this raises an NameError: name 'variable1' is not defined. Did you mean: 'variable2'?.

To be clear, my question is not how to check if a variable exists. My question is how to check if two variables exist with Boolean operators.

I am fully aware that I have commented out variable1. That is the whole point.

Edit: Since this question got duped as this one, I must state that this is not about finding variables in a list. Therefore it is not the same question.

Asked By: Arete

||

Answers:

if 'variable1' and 'variable2' in locals():

can be correctly expressed as

if ('variable1' in locals()) and ('variable2' in locals()):

As for your NameError: you are executing the print after determining that 'variable1' is not in locals() (in Python, indentation matters), so this is the behavior you should expect.

Answered By: Scott Hunter
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.