You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python税务计算器if-else逻辑异常:收入低于20000时执行后续代码报错

Python税务计算器逻辑错误解决方案:未终止执行导致NameError

你的问题核心是:当输入收入低于20000时,程序仅打印提示但未停止运行,后续代码仍会执行,而dep变量只在else分支中定义,因此触发NameError。下面提供两种可行的解决方案:

方案1:在if分支中终止程序

通过引入sys模块调用sys.exit(),在打印提示后直接终止程序,避免后续代码执行:

import sys

taxr = 0.2  # 设置默认税率
stdded = 10000  # 设置标准扣除额
depded = 2000  # 设置被赡养人扣除额
income = int(input("Enter your income: "))  # 用户输入收入

if income < 20000:
    print('Your income is not taxable')
    sys.exit()  # 终止程序
else:
    dep = int(input('Enter how many dependants you have: '))  # 收集被赡养人数量

# 以下代码仅在收入>=20000时执行
dedincome = income - stdded - (depded * dep)  # 计算扣除后收入
incometax = dedincome * taxr  # 计算所得税额
gross = income - incometax  # 计算税后收入

print()  # 空行分隔
print('Your income tax is $', incometax)
print('Your income after tax is $', gross)

方案2:将后续计算代码缩进至else分支

把所有需要在收入达标时执行的计算和打印代码,全部缩进放到else块内,这样当收入低于20000时,这些代码不会被执行:

taxr = 0.2  # 设置默认税率
stdded = 10000  # 设置标准扣除额
depded = 2000  # 设置被赡养人扣除额
income = int(input("Enter your income: "))  # 用户输入收入

if income < 20000:
    print('Your income is not taxable')
else:
    dep = int(input('Enter how many dependants you have: '))  # 收集被赡养人数量
    dedincome = income - stdded - (depded * dep)  # 计算扣除后收入
    incometax = dedincome * taxr  # 计算所得税额
    gross = income - incometax  # 计算税后收入
    
    print()  # 空行分隔
    print('Your income tax is $', incometax)
    print('Your income after tax is $', gross)

错误原因说明

你最初的代码中,if分支仅执行了打印语句,后续的计算代码没有被包含在任何分支内,因此无论收入是否达标,这些代码都会运行。当收入低于20000时,dep变量从未被定义,执行depded*dep时自然会触发NameError。

内容的提问来源于stack exchange,提问作者Marcus fowler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:12:25