8

我是 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'

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

4

3 回答 3

7

为了调用函数,您必须在函数名称之后添加括号以及任何必需的参数。

在这两行

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)))
于 2012-10-16T21:05:10.323 回答
0

我认为问题在于这一行minMonPay = minimumMonthlyPayment,在我看来,您正在将变量分配给方法而不是调用该方法。

于 2012-10-16T21:01:39.730 回答
0

查看您的代码,您似乎正在将一个函数分配给一个变量,然后尝试从一个值中减去一个函数。

您定义了函数“minimumMonthlyPayment(previousbalance)”,然后将该函数分配给变量“minMonPay = minimumMonthlyPayment”。然后稍后你说previousBalance - minMonPay。我认为你的意思是:

minMonPay = minimumMonthlyPayment(previousbalance)

希望有帮助。

于 2012-10-16T21:03:19.240 回答