-1

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.

Arete
  • 948
  • 3
  • 21
  • 48
  • 2
    This is a mixture of "variable variables" and "check multiple values in list" – quamrana Sep 29 '22 at 12:20
  • It's not really "variable variables". The name of the variable doesn't change. The existence of the variable does. Also, I don't see where the list comes in here. – Arete Oct 01 '22 at 15:33
  • The [variable variables](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) refers to creating some variables, but not others: The names should be keys to a `dict`. The [list](https://stackoverflow.com/questions/18676823/checking-if-two-variables-are-in-the-same-list) is where you are checking the two names in `locals()` – quamrana Oct 01 '22 at 17:13

1 Answers1

4
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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101