Python中两个相似的if循环之间的区别

时间:2018-01-15 11:55:47

标签: python python-3.x python-2.7

我有两个代码应该执行相同的操作,但在第一个,我没有得到结果,但在第二个我得到输出

    if (Method == "EMM" ):
        if ((Loan_Obligation/12)+EMI) !=0:
            DSCR_Post = EBITDA_EMM/((Loan_Obligation/12)+EMI) 
        else:
            0
    elif (Method != "EMM" ):
        if ((Loan_Obligation/12)+EMI) !=0:
            DSCR_Post = EBITDA/((Loan_Obligation/12)+EMI)
        else:
            0

和另一个是:

    if (Method == "EMM"):
        DSCR_Post = EBITDA_EMM/((Loan_Obligation/12)+EMI) if ((Loan_Obligation/12)+EMI) !=0 else 0
    else:
        DSCR_Post = EBITDA/((Loan_Obligation/12)+EMI) if ((Loan_Obligation/12)+EMI) !=0 else 0
    print('DSCR_Post:',DSCR_Post)

有人可以帮我解释两个代码之间的区别

1 个答案:

答案 0 :(得分:0)

在您的第一个代码段中,您没有像在第二个代码段中那样将0分配给DSCR_Post。修改如下:

if Method == "EMM" :
    if (Loan_Obligation / 12) + EMI !=0:
        DSCR_Post = EBITDA_EMM / ((Loan_Obligation / 12) + EMI) 
    else:
        DSCR_Post = 0  # the 0 has to be assigned!
else:  # you do not need a condition here! It can either be equal or not, no third state possible.
    if (Loan_Obligation / 12) + EMI !=0:
        DSCR_Post = EBITDA / ((Loan_Obligation / 12) + EMI)
    else:
        DSCR_Post = 0
print('DSCR_Post:',DSCR_Post)

可以简化为以下内容:

ebid = EBITDA_EMM if Method == "EMM" else EBITDA
DSCR_Post = 0  # 0 will be overwritten if ...
if (Loan_Obligation / 12) + EMI != 0:
    DSCR_Post = ebid / ((Loan_Obligation / 12) + EMI) 
print('DSCR_Post:',DSCR_Post)