触发NameError求助:输入Bond选项时提示名称未定义
问题排查与解决
核心原因
输入Bond选项时触发的NameError,主要是执行完Bond分支代码后,程序继续运行到下方的if y == 'Simple'语句时,变量y从未被定义过,Python找不到该变量就会抛出错误。
另外还有一个潜在语法问题:elif greeting == "Bond"是孤立的,elif必须紧跟在if或其他elif之后,不能单独使用,如果前面没有对应的if语句,也会触发语法错误。
修复方案
- 将投资计算代码归到对应分支
投资相关的判断逻辑属于Investment选项,需要嵌套到if greeting == "Investment"分支内,避免执行Bond选项时走到这段未定义变量的代码。示例代码如下:# 先通过if语句承接后续的elif if greeting == "Investment": investment = float(input("Enter the amount you want to invest: ")) rate = float(input("Enter the interest rate percentage: ")) / 100 years = int(input("Enter the number of years: ")) y = input("Choose 'Simple' or 'Compound' interest: ") if y == 'Simple': # 修正单利公式:原代码误用了复利公式 total = investment * (1 + rate * years) print(f"The total amount after {years} years will be {total:.2f}") elif y == 'Compound': total = investment * math.pow((1 + rate), years) print(f"The total amount after {years} years will be {total:.2f}") elif greeting == "Bond": house_value = int(input('Please enter the value of the house: ')) monthly_rate = float(input('Enter the percentage of your interest rate: ')) / 100 / 12 monthly_repay = int(input('Please enter the number of months you plan to take to repay the bond: ')) x = (monthly_rate * house_value) / (1 - (1 + monthly_rate)**(-monthly_repay)) print(f"The monthly repayment is {x:.2f}") - 修正公式逻辑错误
原代码中if y == 'Simple'分支误用了复利计算公式,单利的正确公式为:本息和 = 本金 × (1 + 年利率 × 年数)。 - 确保变量提前定义
所有用到的变量(如greeting、y、investment等)必须在使用前通过输入或赋值完成定义,避免出现未定义的情况。
内容的提问来源于stack exchange,提问作者Dave Griffin
相关产品推荐
相关产品推荐

