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

2024-09-28 01:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

    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)

有人能帮我一下这两种代码有什么区别吗


Tags: 代码if事情postelsemethodprintelif
1条回答
网友
1楼 · 发布于 2024-09-28 01:22:58

在第一个代码段中,没有像在第二个代码段中那样将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)

相关问题 更多 >

    热门问题