Search code examples
pythonpython-3.xif-statementconditional-statementsconditional-operator

Python 3 conditional variable selection increment


I'm currently working on a project where a lot of different accounting is done and I came to see this pattern very often:

if A > X:
    B += 1
else:
    C += 1

I know ternary operator but if I understand it correctly the shortest way how to utilize it would be:

B += 1 if A > X else False
C += 1 if A <= X else False

since ternary operator is connected to the variable used in its head. So using ternary operator is obviously worse than the previous if/else both from computational and readability standpoint.

The other idea was to create a simple function like this:

conditional_bumper(positive_case_var, negative_case_var, condition_var, compare_to=0)

then the usage looks like:

conditional_bumper(B, C, A, X)  # X being optional

so I can one line it every time I see it but at the same time this seems to me like a very 'hacky' solution. Is there a better way I don't see?


Solution

  • Try this Pal! Hope this gives you a north of this matter. Cheers!

        # declare and initialize variables
        B, C = 0, 0
        A, X = 1, 2
        
        # ternary operator to work with this conditional
        B,C = (B + 1, C) if A > X else(B,C + 1)
        
        #display results
        print(B,C)