Anas
Anas

Reputation: 742

Python avoid nesting when checking multiple conditions

I have this python conditions

a=a_foo()
if a==True:
  b=b_foo():
    if b==True:
      c=c_foo()
      if c==True:
         d=d_foo()
      else:
        print('c error')
    else:
      print('b error')
  else:
    print('a error')

The code is working, but if i use this conditions for a-z, the code seems bad.

What a better solution ?

EDIT :

Thanks for comment, i will use if a instead of if a == True

also a_foo, b_foo, c_foo functions is only example, can be function1,func2,funcother,etc

and last, the function also have parameter, example a_foo(p1, p2)

Upvotes: 0

Views: 173

Answers (4)

quamrana
quamrana

Reputation: 39354

You just need to list the functions that you want to call. However, you will need some way of identifying which function failed:

funcs = [a_foo,b_foo,c_foo,d_foo]   # add more functions as required

for f in funcs:
   if not f():
        print(f.__name__, "error")
        break

If you want to have different sets of parameters with each function:

funcs = [(a_foo,),(b_foo,b),(c_foo,c,d),(d_foo,d,e,f)]   # add more functions as required

for f,*args in funcs:
   if not f(*args):
        print(f.__name__, "error")
        break

Upvotes: 3

asikorski
asikorski

Reputation: 922

You can simply put functions and messages into a list of tuples:

# each element is a tuple with a function to execute and error message when result is False
functions_with_messages = [(a_foo, 'a error'), (b_foo, 'b error'), (c_foo, 'c error')]

for function, error_message in functions_with_messages:
    function_result = function()
    if not function_result:
        print(error_message)
        break  # optional if you want to stop execution of next functions

It would be more idiomatic than the hack-y way of getting function's name with function.__name__. It can be also easily translated into other programming languages.

Upvotes: 2

Enes Doğan
Enes Doğan

Reputation: 29

2 line solution here.

from string import ascii_lowercase
[print(i) for i in ascii_lowercase if eval(f'{i}_foo()')]

Upvotes: -2

Charles Duffy
Charles Duffy

Reputation: 295363

Put this in a function and then you can return from it so there's no need to keep nesting.

a = a_foo()
if not a:
    print('a error')
    return

b = b_foo()
if not b:
    print('b error')
    return

Upvotes: 0

Related Questions