Python TypeError:不支持的操作数类型 - :'int'和'function'

时间:2012-10-16 20:55:52

标签: python typeerror

我是Python的初学者,正在完成作业。在研究错误并应用建议的修复程序后,我不断获得TypeError: unsupported operand type(s) for -: 'int' and 'function'。我不是在寻找任何人给我一个解决方案,但我会很感激第二眼。我错过了什么,但我不知道是什么。这是我遇到问题的代码部分:

month = 0
interestYDT = 0
balance = int(raw_input ("Enter balance on credit card: "))
annualInterestRate = float(raw_input ("Enter annual interest rate as a decimal: "))
monthlyPaymentRate = float(raw_input ("Enter minimum monthly payment rate as a decimal: "))
previousbalance = balance
#
def monthlyInterestRate(annualInterestRate):
    return float(annualInterestRate/12)
#
if month <= 12:
    def minimumMonthlyPayment(previousbalance):
        return (previousbalance * monthlyPaymentRate)
    def monthlyInterest(monthlyInterestRate):
        return (1 + monthlyInterestRate)
    minMonPay = minimumMonthlyPayment
    monInt = monthlyInterest
    newbalance = ((previousbalance - minMonPay) * (monInt))
    interestYDT = (interestYTD + montInt)
    previousbalance = (newbalance)
    print ''
    print ('Month:' (month))
    print ('Minimum monthly payment: $ ' (round(minimumMonthlyPayment, 2)))
    print ('Remainging balance: $ ' (round(newbalance, 2)))
    print ' '
    month = (month + 1)

这是我得到的整个错误:

Traceback (most recent call last):
  File "C:/Users/Karla/Documents/_MIT 600X Introduction to CS and Prog/Assignments/Week2/kmarciszewski_week2_Problemset_Problem1.py", line 33, in <module>
    newbalance = ((previousbalance - minMonPay) * (monInt))
TypeError: unsupported operand type(s) for -: 'int' and 'function'

我真的很感激任何见解。谢谢。

3 个答案:

答案 0 :(得分:5)

要调用函数,必须在函数名后添加parens,以及任何必需的参数。

在这两行中

minMonPay = minimumMonthlyPayment
monInt = monthlyInterest

将函数分配给名称minMonPay,monInt,但实际上并没有调用它们。相反,你需要写一些类似的东西:

minMonPay = minimumMonthlyPayment(previousBalance)
monInt = monthlyInterest(monthlyInterestRate)

这个定义

def minimumMonthlyPayment(previousbalance):
    return (previousbalance * monthlyPaymentRate)

为您提供一个函数,它接受一个参数并将其称为previousBalance。它与您之前在代码中创建的变量无关。事实上,我建议你重命名它,它只能让你作为一个初学者迷惑。

此外,您创建的功能非常简单,每次只使用一次,您可能有兴趣删除它们并内联代码。

# OLD CODE
def minimumMonthlyPayment(previousbalance):
    return (previousbalance * monthlyPaymentRate)
def monthlyInterest(monthlyInterestRate):
    return (1 + monthlyInterestRate)
minMonPay = minimumMonthlyPayment
monInt = monthlyInterest

# NEW CODE
minMonPay = previousbalance * monthlyPaymentRate
monInt = 1 + monthlyInterestRate

如果这样做,请不要忘记更新错误使用minimumMonthlyPayment函数的行。

# OLD CODE
print ('Minimum monthly payment: $ ' (round(minimumMonthlyPayment, 2)))

# NEW CODE
print ('Minimum monthly payment: $ ' (round(minMonPay, 2)))

答案 1 :(得分:0)

我认为问题在于这一行minMonPay = minimumMonthlyPayment它让我觉得你正在为方法分配变量而不是调用方法。

答案 2 :(得分:0)

查看您的代码,看起来您正在为变量分配函数,然后尝试从值中减去函数。

您定义函数'minimumMonthlyPayment(previousbalance)',然后将函数分配给变量'minMonPay = minimumMonthlyPayment'。然后你说previousBalance - minMonPay。我认为你打算做的是:

minMonPay = minimumMonthlyPayment(previousbalance)

希望有所帮助。