0

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)

0

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

how if each function have different parameter
this is what i looking for, thanks for answer
2

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.

Comments

0

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

Comments

-2

2 line solution here.

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

3 Comments

It's a nice one-liner but using eval is bad in general, see Why is using eval a bad practive?.
I know but still it's a one-liner.
It might be a one-liner, but it is not a good solution. Just because you can do a thing, doesn't mean you should do a thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.