如何将if语句的结果赋给等式?

2024-05-23 19:30:20 发布

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

我是python新手,我必须运行一个程序,根据用户输入获得正确的利率,并使用获得的利率来计算每月赚取的利息。你知道吗

对于利息收入的计算,我尝试使用打印结果来创建计算每月利息收入的公式。然而,我已经尝试了这么多的事情,我不知道如何纠正这一点。你知道吗


transaction_category = [2000, 2500, 5000, 15000, 30000]
first_50k_1_category_rates = [0.05, 1.55, 1.85, 1.90, 2.00, 2.08]

if (count == 1) and (account_balance <= 50000) and (total_eligible_monthly_transactions < transaction_category[0]):
    print(f'Interest rate applicable is: {first_50k_1_category_rates[0]: .2f}%')

if (count == 1) and (account_balance <= 50000) and (transaction_category[0] <= total_eligible_monthly_transactions < transaction_category[1]):
    print(f'Interest rate applicable is: {first_50k_1_category_rates[1]: .2f}%')


Tags: andifcountaccounttotalfirsttransactiontransactions
3条回答

如果你在范围上有问题,你可以试试这个(安全的)黑客:

_scope = {
    "applicable_interest_rate1": first_50k_1_category_rates[4],
    "applicable_interest_rate2": first_50k_1_category_rates[5],
}

def foo(condition1, condition2):

    if condition1 < condition2:
        result = _scope["applicable_interest_rate1"]

    if 1 == False:
        result = _scope["applicable_interest_rate2"]

    return result


print(foo(1, 2))

你的问题不太清楚,但我猜你在找类似的问题

if (count == 1) and (account_balance <= 50000) and (transaction_category[3] <= total_eligible_monthly_transactions < transaction_category[4]):
    applicable_interest_rate = first_50k_1_category_rates[4]

elif (count == 1) and (account_balance <= 50000) and (total_eligible_monthly_transactions >= transaction_category[4]):
    applicable_interest_rate = first_50k_1_category_rates[5]

print(f'Interest rate applicable is: {applicable_interest_rate: .2f}%')

这只是一个草图;您必须确保始终定义了新变量,然后在最终公式中使用它。你知道吗

可能重复的条件也应该被重构,这样你就不会一遍遍地比较相同的东西了。你知道吗

if (count == 1) and (account_balance <= 50000):
    if transaction_category[3] <= total_eligible_monthly_transactions < transaction_category[4]:
        applicable_interest_rate = first_50k_1_category_rates[4]
    elif total_eligible_monthly_transactions >= transaction_category[4]:
        applicable_interest_rate = first_50k_1_category_rates[5]

但是,在没有看到完整脚本的情况下,还不清楚如何重构。这只是一个例子来说明这个想法。你知道吗

因此,您可以在一个代码块中执行if/else,或者将这些print语句转换为变量并返回它们。两者都将result作为var名称。你知道吗

def foo(condition1, condition2):

    if condition1 < condition2:
        result = (1 + 1)

    if 1 == False:
        result = (1 - 1)

    return result

print(foo(1, 2))
  • 有更好的方法可以在函数式编程方面做到这一点:(lambda :f"b:{b}",lambda :f"a:{a}")[a>b](),但似乎这种代码风格是必要的,所以坚持这样做。你知道吗

相关问题 更多 >