Python实现商品折扣计算脚本报字符串与浮点拼接TypeError求助
问题排查及修复方案
错误点汇总
- 类型拼接错误:
print('Total price = ' + totalprice)中字符串不能直接和浮点数类型相加,需要先做类型转换或者使用格式化输出 - 未定义变量错误:代码中错误使用了不存在的变量
var3,实际要调用的是提前定义好的税率乘数addtax - Python版本兼容问题:如果运行环境是Python3,
raw_input已经被废弃,需要替换为input - 输出格式不符合要求:没有对输出数值做两位小数格式化,无法匹配预期的
.00/.36这类展示效果 - 逻辑冗余:原代码拆分了多组重复判断,维护性差,可合并简化
修复后完整代码
# 获取用户输入的基础价格 item1 = float(input('Enter the price of the first item: ')) item2 = float(input('Enter the price of the second item: ')) clubc = input('Does customer have a club card? (Y/N): ') tax = float(input('Enter tax rate, e.g. 5.5 for 5.5% tax: ')) basep = item1 + item2 print(f'Base price = {basep:.2f}') # 计算税率乘数 addtax = 1 + tax / 100 # 计算低价商品半价后的金额 if item1 >= item2: discount_p = item1 + item2 / 2 else: discount_p = item2 + item1 / 2 # 计算会员卡折扣 if clubc == 'Y': priceafterd = discount_p * 0.9 else: priceafterd = discount_p print(f'Price after discounts = {priceafterd:.2f}') # 计算含税总价 totalprice = priceafterd * addtax print(f'Total price = {totalprice:.2f}')
测试验证
输入测试用例10、20、Y、8.25,输出结果完全符合预期:
Base price = 30.00 Price after discounts = 22.50 Total price = 24.36
内容的提问来源于stack exchange,提问作者SupaDupa23
相关产品推荐
相关产品推荐

