Home > front end >  Python is it possible to put two if and one else statements together?
Python is it possible to put two if and one else statements together?

Time:02-03

if 'a' in dict:
    dict['a'] do something
if 'b' in dict:
    dict['b'] do something
# After checking the above two if statements, run the else statement below
else:
    dict do something

I'd like to check if 'a' or 'b' in dict. If I use elif statement, then checking 'b' would be skipped if 'a' is in dict.

Is it possible to check the above 2 cases, if both 'a' and 'b' not in dict, then we else to do something else?

I can implement it in a tedious way though.

if `'a' or 'b'` in dict:
    if 'a' in dict:
        dict['a'] do something
    if 'b' in dict:
        dict['b'] do something
else:
    dict do something

CodePudding user response:

dictionary = {"a":1, "b":2}
if (cond1 := "a" in dictionary) | (cond2 := "b" in dictionary):
    if cond1:
        pass
    if cond2:
        pass
else:
    pass

Using somewhat recent addition to the language - := operator you can capture the value of both conditions. While you still need to check if they are true or false separately, it lets you skip repeating the same check twice.

| has to be used instead of or due to lazy evaluation of the latter - if cond1 is True, 2nd condition will never be checked and cond2 will be undefined. | will make sure both conditions are checked, but it makes the solution not as pretty as it should be.

CodePudding user response:

There's no way to have the ifs only check one of a or b, but then somehow have the else take account of both a and b at once. If you want to have one code branch for a alone, one for b alone, and one for the combination (or its negation), you need three ifs somehow or other. Your "tedious" example with nested ifs is a perfectly reasonable solution.

It's hard to tell from the question exactly what you would consider a satisfying alternative, but here's one:

if 'a' in d:
    do_something(d['a'])
if 'b' in d:
    do_something(d['b'])
if 'a' not in d and 'b' not in d:
    do_something_else()

This avoids the extra level of nesting by making a third if that just checks for the negation of the disjunction of the earlier two conditions. This isn't really any better than your "tedious" solution though.

CodePudding user response:

Here's an idea - first check if none of the relevant keys are present; if that's False, then execute the relevant action for each relevant key that is indeed present.

This can be simplified if you have another dictionary where you keep the relationship of each key: action associated (this means that your do somethings should become proper functions).

Something like:

# Put your logic for each key here
def do_something_no_keys(): 
    print('No keys found!')

def do_something_a(): 
    print('Key "a" found!')

def do_something_b(): 
    print('Key "b" found!')

# Associate each possible key with their logic here
action_dict = {
    'a': do_something_a,
    'b': do_something_b,
}

# These are the values that you want to check
value_dict = {
    'a': 'foo',
    'c': 'bar',
}

if all(key not in value_dict for key in action_dict):
    do_something_no_keys()
else:
    for key, action in action_dict.items():
        if key in value_dict:
            action()

Current output is Key "a" found!, but you can see this change if you modify the keys in the value_dict.

CodePudding user response:

Reducing checks, using ideas from other answers:

if first := "a" in dictionary:
    print("a")
if "b" in dictionary:
    print("b")
elif not first:
    print("Neither")

CodePudding user response:

neither_a_nor_b = True

if 'a' in dict:
    neither_a_nor_b = False
    # suite 1

if 'b' in dict:
    neither_a_nor_b = False
    # suite 2

if neither_a_nor_b:
    # suite 3

If suites 1 and 2 are the same, you can use a loop:

neither_a_nor_b = True

for x in ['a', 'b']:
    if x in dict:
        neither_a_nor_b = False
        # suite 1/2

if neither_a_nor_b:
    # suite 3

Though in either case, you might simply replace neither_a_nor_b with an explicit (if redundant) test like all(x not in dict for x in ['a', 'b']).

CodePudding user response:

You can stack if statements and use an elif statement:

dictionary = {"a": 1, "b": 2}
    if "a" in dictionary:
        print("a")
    if "b" in dictionary:
        print("b")
    elif "a" not in dictionary and "b" not in dictionary:
        print("Neither")

Prints:

a
b

While

dictionary = {"z": 1, "x": 2}
    if "a" in dictionary:
        print("a")
    if "b" in dictionary:
        print("b")
    elif "a" not in dictionary and "b" not in dictionary:
        print("Neither")

Prints:

Neither

CodePudding user response:

If you are using a for to loop through the dict you can use the continue statement like this:

for el in dict:
  if 'a' in el:
      do something
      continue
  if 'b' in el:
      do something
      continue
  else:
      do something
  •  Tags:  
  • Related