Home > Software design >  How to add if and else condition within a return in python? Similar to using case when within a Case
How to add if and else condition within a return in python? Similar to using case when within a Case

Time:12-13

Currently I have my function with if, return, elif, return and else return statement/conditions.

I would like to add couple if and else condition within my return in python. Within my calculation, I need to either add or subtract but this depends different conditions. I need help in replicating the below SQL case statement in python.


SET AccruedInterest =
   CASE WHEN scheduleleg ='L' THEN 1 ELSE -1 END
   * Principal
   *(AllInRate /100)
   *(360 *(Year@(ReportDate) - Year@(StartDate)   30 * (Month@(ReportDate) - Month@(StartDate))
        CASE WHEN DAY(ReportDate) > 30 THEN 30 ELSE DAY(ReportDate) END
      - CASE WHEN DAY(StartDate) > 30 THEN 30 ELSE DAY(StartDate) END
   /360
WHERE Basis ='30/360'

I specifically need to add below conditions into my python function.

  CASE WHEN DAY(ReportDate) > 30 THEN 30 ELSE DAY(ReportDate) END
- CASE WHEN DAY(StartDate) > 30 THEN 30 ELSE DAY(StartDate) END

This is my current function and conditions in Python.

#Accrued Calc for 30/360 Basis 
def accrued_30_360(row):
    if row['Type'] == 'L' and row['Current Filter'] == 'Current CF':
        return 1 * row['Principal/GrossAmount'] * (row['All in Rate']/100)* (360 *(Settlement.year - row['Start Date YEAR'])   30 * (Settlement.month - row['Start Date MONTH'])
    elif row['Type'] == 'D':
        return -1 * row['Principal/GrossAmount'] * (row['All in Rate']/100)* (360 *(Settlement.year - row['Start Date YEAR'])   30 * (Settlement.month - row['Start Date MONTH'])
    else:
        return ''

Thanks

CodePudding user response:

Instead of working from top to bottom of your SQL query, you should work from bottom to top of it to simplify your code, since you haven't specified some of the fields in your DB, you might have to replace some of them below -


def accrued_30_360(row):
    extra_days = 0
    if row['ReportDate'].day > 30:
        extra_days  = 30
    else:
        extra_days  = row['ReportDate'].day

    if row['StartDate'].day > 30:
        extra_days -= 30
    else:
        extra_days -= row['StartDate'].day

    years = (360 *(Settlement.year - row['Start Date YEAR'])   30 * (Settlement.month - row['Start Date MONTH'])   extra_days)/360
    amount = row['Principal/GrossAmount'] * (row['All in Rate']/100)* years
    multiplier = 1 if (row['scheduleleg'] == 'L') else -1 # update this condition
    final_value = multiplier * amount
    return final_value

CodePudding user response:

You can do that using the inline if syntax:

How to write inline if statement for print?

For example:

a = (1 if True else 0)   5 
  • Related