尝试写入 Python 闭包的语法无效
Invalid Syntax attempting to write Python closure
我正在尝试编写一个函数(在 Python 2.7 中),该函数需要未清余额和年利率,然后 return 使用二分法搜索将每月最低付款额精确到最接近的美分 to solve problem #3。我试图通过在主函数中编写一个函数来遵循 DRY 原则,该函数应该 return 一个列表,其中包含一年后的余额和月数(如果余额达到零或更少,循环应该中断),这将需要在我的主要功能中计算两次。当我在继续之前尝试测试这个初始闭包时,我在分配 monthlyPayment
的行上遇到语法错误。我做错了什么?
# Problem Set 1("C")
# Time Spent: xx hours
def payInOne_BisectionSearch (balance,annualRate):
#initialize variables
initialBalance = balance
monthlyRate = annualRate/12
minMonthly = balance/12
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
monthlyPayment = (minMonthly + maxMonthly)/2
numMonths = 1
#define function to check balance after 12 months
def balanceAfterYear (balance, monthlyRate, monthlyPayment):
for numMonths in range (1,13):
interest = balance * monthlyRate
balance += interest - monthlyPayment
if balance <= 0:
break
return [balance, numMonths]
resultList = balanceAfterYear(initialBalance, monthlyRate, monthlyPayment)
print resultList[0],resultList[1]
payInOne_BisectionSearch (input("Enter the outstanding balance"),input("Enter annual rate as a decimal"))
您忘记了上一行的右括号。
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
我正在尝试编写一个函数(在 Python 2.7 中),该函数需要未清余额和年利率,然后 return 使用二分法搜索将每月最低付款额精确到最接近的美分 to solve problem #3。我试图通过在主函数中编写一个函数来遵循 DRY 原则,该函数应该 return 一个列表,其中包含一年后的余额和月数(如果余额达到零或更少,循环应该中断),这将需要在我的主要功能中计算两次。当我在继续之前尝试测试这个初始闭包时,我在分配 monthlyPayment
的行上遇到语法错误。我做错了什么?
# Problem Set 1("C")
# Time Spent: xx hours
def payInOne_BisectionSearch (balance,annualRate):
#initialize variables
initialBalance = balance
monthlyRate = annualRate/12
minMonthly = balance/12
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
monthlyPayment = (minMonthly + maxMonthly)/2
numMonths = 1
#define function to check balance after 12 months
def balanceAfterYear (balance, monthlyRate, monthlyPayment):
for numMonths in range (1,13):
interest = balance * monthlyRate
balance += interest - monthlyPayment
if balance <= 0:
break
return [balance, numMonths]
resultList = balanceAfterYear(initialBalance, monthlyRate, monthlyPayment)
print resultList[0],resultList[1]
payInOne_BisectionSearch (input("Enter the outstanding balance"),input("Enter annual rate as a decimal"))
您忘记了上一行的右括号。
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12