Home > Mobile >  Python elegant way for many conditional statements in if statement
Python elegant way for many conditional statements in if statement

Time:05-18

Is there a better more elegant / professional way to code the following

if A > 1 and B > 1 and C > 1 and A < 100 and B < 100 and C < 100:
    do something

?

CodePudding user response:

Use the all() function, as well as chained comparisons

if all(1 < x < 100 for x in (A, B, C)):
    # do something

CodePudding user response:

Use all() rather than listing out each condition. This will make it easier to add new variables to check, if necessary:

if all(1 < item < 100 for item in [A, B, C]):
    do something
  • Related