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.