[英]How to add if and else condition within a return in python? Similar to using case when within a Case statement in SQL
Currently I have my function with if, return, elif, return and else return statement/conditions.目前我的 function 带有 if、return、elif、return 和 else return 语句/条件。
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.我想在 python 的回报中添加几个if 和 else 条件。在我的计算中,我需要添加或减去,但这取决于不同的条件。 I need help in replicating the below SQL case statement in python.
我需要帮助在 python 中复制以下 SQL 案例陈述。
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.我特别需要将以下条件添加到我的 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 .这是我当前的 function 和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谢谢
You can do that using the inline if
syntax:您可以使用内联
if
语法来做到这一点:
How to write inline if statement for print? 如何编写用于打印的内联 if 语句?
For example:例如:
a = (1 if True else 0) + 5
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 -不要从上到下处理 SQL 查询,您应该从下到上处理它以简化代码,因为您没有在数据库中指定某些字段,您可能必须在下面替换其中的一些 -
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.