How can I simplify these conditions, is there any way?

1

Is there any way to simplify these conditions to a shorter one?

    saldo_mes_corriente= CreditoBd.objects.filter(fecha_reporte=fecha_cierre).aggregate(Sum('saldo_credito'))
    saldo_mes_anterior= CreditoBd.objects.filter(fecha_reporte=fecha_cierre_anterior).aggregate(Sum('saldo_credito'))

    if saldo_mes_corriente > saldo_mes_anterior:
        icono_saldo = '+'
    else:
        if saldo_mes_corriente < saldo_mes_anterior:
            icono_saldo = '-'
        else:
            icono_saldo = '0'
    
asked by Ernestoruiz89 28.10.2017 в 21:34
source

2 answers

1

The only recommendation I would make would be to use elif , and in that way avoid nesting that conditional:

if saldo_mes_corriente > saldo_mes_anterior:
    icono_saldo = '+'
elif saldo_mes_corriente < saldo_mes_anterior:
    icono_saldo = '-'
else:
    icono_saldo = '0'

It is preferable not to sacrifice readability, because you may be able to shorten your code but if in the end it is more difficult to read, you will not have gained much.

    
answered by 28.10.2017 / 23:22
source
0

I do not think you can simplify much. Just as an alternative you can use the syntax of the ternary operator:

icono_saldo = "+" if saldo_mes_corriente > saldo_mes_anterior else\
              "-" if saldo_mes_corriente < saldo_mes_anterior else "0"

Another thing is that the loss of legibility deserves it. At the efficiency level, the differences between your code, ternary operator or a elif are negligible.

    
answered by 28.10.2017 в 22:04