Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested conditions in python

Tags:

python

I am trying to figure out the shortest, most pythonic way to implement a similar to the following syntax:

if A and (B if C):
    print(A)

in a way that:

  • if C is False, then B is omitted (therefore (B if C) is True).
  • if C is True, then B is evaluated, effectively making the syntax if A and B:

This can be made through various separate if statements, but my ultimate purpose with this was to make it into a list comprehension for a value assignment.

Edit:

The list comprehension I wanted to make was this:

methods = [name for (name, func) in locals().items() \
    if callable(func) and (not __name__ == '__main__' or \
    func.__module__ == __name__)]

So that it returns the function names I have defined in that module as well as if methods is imported from the outside.

like image 778
mariogarcc Avatar asked Jun 06 '26 00:06

mariogarcc


1 Answers

This should be equivalent, if my old statement logic doesn't fail me =)

if A and (not C or B):
    print(A)

Explanation: "B if C" <=> C -> B <=> not C or B

Expression B is only evaluated if C holds.

like image 200
user2390182 Avatar answered Jun 07 '26 12:06

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!