IF条件Python“本地变量'monthlyPayment'在赋值之前被引用”

时间:2016-10-25 05:56:38

标签: python if-statement

在以下示例中,我收到错误

“local variable 'monthlyPayment' referenced before assignment”

以下是我的代码

def getMonthlyPayment(self, annualInterestRate, loanAmount, numberOfYears, loan):

    if loan == 0 and (annualInterestRate * 1 - loanAmount) >= 2 and numberOfYears <= 3:
        monthlyPayment = min((annualInterestRate * 1 - loanAmount), 10)
        return monthlyPayment
    elif loan == 1 and (annualInterestRate * 2 - loanAmount) >= 2 and numberOfYears <= 3:
        monthlyPayment = min((annualInterestRate * 2 - loanAmount), 20)
        return monthlyPayment
    elif loan > 1 and (annualInterestRate * 4 - loanAmount) >= 2 and numberOfYears <= 3:
        monthlyPayment = min((annualInterestRate * 4 - loanAmount), 20)
        return monthlyPayment
    else:
        monthlyPayment = 'Not Qualify'
        return monthlyPayment

2 个答案:

答案 0 :(得分:0)

您的代码格式不正确。此外,不需要多个WebView。删除除最后一个之外的所有返回。

此外,您没有在函数中的任何位置使用return,请使用带有类函数的@staticmethod装饰器。

以下是代码,假设您的所有逻辑都是正确的:

self

答案 1 :(得分:0)

多个else if语句的正确结构是

if (condition):
  monthlypayment = something
elif (condition2):
  monthlypayment = something2
elif (condition3):
  monthlypayment = something3
else:
  monthlypayment = something4

因此,如果您的if语句格式正确,则每月付款将只分配一次值。按照上面的@匿名评论,您可以使用return monthlypayment

结束该功能

假设此函数是类定义的一部分,则需要self或@staticmethod装饰器。如果您正在编写非面向对象的代码,则可以省去自己。

def getMonthlyPayment(self,annualInterestRate,loanAmount,numberOfYears,loan):
    if  loan == 0 and (annualInterestRate * 1 - loanAmount) >= 2 and numberOfYears <= 3:
       monthlyPayment = min((annualInterestRate * 1 - loanAmount), 10)
    elif   loan == 1 and (annualInterestRate * 2 - loanAmount) >= 2 and numberOfYears <= 3:
       monthlyPayment = min((annualInterestRate * 2 - loanAmount), 20)
    elif   loan > 1 and (annualInterestRate * 4 - loanAmount) >= 2 and numberOfYears <= 3:
       monthlyPayment = min((annualInterestRate * 4 - loanAmount), 20)
    else:
       monthlyPayment='Not Qualify'
    return monthlyPayment