python 名称错误:'pay_off' 未定义

-1 投票
2 回答
1829 浏览
提问于 2025-04-18 16:06

当我这样写代码的时候,它运行得很好:

#this block of code will get the necessary inputs from the user

or_balance=balance=float(input('Enter the outstanding balance on your credit card: '))
int_rate=float(input('Enter the annual credit card interest rate as a decimal: '))
mon_int_rate=int_rate/12

#this block of code will deal with the inputs to get the outputs

mon_pay_low_bound=balance/12
mon_pay_up_bound=(balance*(1+mon_int_rate)*12)/12

def total_balance(mon_pay):
    balance=or_balance
    global num
    num=0
    while num<12:
        num+=1
        balance=balance*(1+mon_int_rate)-mon_pay

    return balance

#this block of code will get the result desired by using the bisection method

a=mon_pay_low_bound
b=mon_pay_up_bound
tol=.0000000000005
n=1
while n<999:
    c=(a+b)/2
    if total_balance(c)==0 or (b-a)/2<tol:

        break
    else:
        n+=1
        if total_balance(c)<0:
            b=c
        else:
            a=c

#this block of code will give the final results
print('RESULT')
print('Monthly payment to pay off debt in 1 year:',round(c,2))
print('Number of months needed:',num)
print('Balance',round(total_balance(c),2))

但是,当我做了下面这些简单的修改:

while n<999:
    c=(a+b)/2
    if total_balance(c)==0 or (b-a)/2<tol:
        pay_off=c
        break
    else:
        n+=1
        if total_balance(c)<0:
            b=c
        else:
            a=c

#this block of code will give the final results
print('RESULT')
print('Monthly payment to pay off debt in 1 year:',round(pay_off,2))
print('Number of months needed:',num)
print('Balance',round(total_balance(pay_off),2))

我遇到了以下错误:

NameError: name 'pay_off' is not defined ,

这是为什么呢?

还有一个问题,我能在不使用全局变量的情况下,从 total_balance() 中获取数字值吗?

2 个回答

0

正如其他人所说的,问题在于 total_balance(c)==0 or (b-a)/2<tol 这个条件从来没有被判断为真。我试过用2000(当前余额)和0.13(利率)作为输入,结果看起来是正确的。需要注意的是,这个结果是经过52次循环才得到的(我在循环结束后加了一个 print n 来查看)。

我觉得你最好的办法是加一个测试,确保真的找到了答案——可以这样做:

pay_off=0
while n<999:
    c=(a+b)/2
    if total_balance(c)==0 or (b-a)/2<tol:
        pay_off=c
        break
    else:
        n+=1
        if total_balance(c)<0:
            b=c
        else:
            a=c
if pay_off == 0:
    print "I couldn't determine the payoff amount in %d iterations" % n

这样无论是否真的达到了 pay_off,都会先初始化它,这样就不会出现 NameError,然后你可以检测并提醒用户算法没有找到好的答案。

试着调整一下 n 的最大值——我试过用 while n<50 来验证如果条件没有达到就会出现 NameError。我怀疑你用的输入情况下,二分法需要超过999次迭代才能找到答案。增加 tol 的值也应该能让你用更少的迭代次数得到答案。

0

如果这个条件 total_balance(c)==0 or (b-a)/2<tol 永远不会变成 True,那么 pay_off 就永远不会被设置。所以当你在最后的打印结果中引用 pay_off 时,如果它还没有被设置,就会出现 NameError 错误。

撰写回答