TCS DCA编程题:Python实现小型杂货店购物计价功能及代码优化
原代码存在的逻辑问题
- 异常分支未终止程序:输入非数字触发
Invalid打印后,后续代码仍会执行,会抛出inp_num、qua未定义的报错 - 商品ID匹配逻辑完全错误:
if([new['id_num']==inp_num])会将布尔Series封装为列表,列表非空所以判断永远为真,哪怕输入不存在的ID也会进入分支 - 缺少库存校验逻辑:完全没有比对购买数量和商品库存,不符合超出库存输出
out of stock的需求 - 总价计算逻辑错误:
price*qua中的price是存储所有商品单价的列表,不是匹配ID对应的单个商品单价,计算结果不符合预期 - 输出格式不匹配要求:没有按照示例输出
total price = xxx的格式,也未处理ID不存在的异常场景
修正后可正常运行的代码
import pandas as pd id_num = [101, 102, 103, 104] price = [40, 50, 60, 70] stock = [10, 14, 14, 13] goods_df = pd.DataFrame({ 'id_num': id_num, 'price': price, 'stock': stock }) try: inp_num = int(input("enter the id number:")) qua = int(input("enter the quantity:")) except ValueError: print("Invalid") exit() # 匹配对应ID的商品 match_res = goods_df[goods_df['id_num'] == inp_num] if match_res.empty: print("Invalid") else: current_stock = match_res.iloc[0]['stock'] current_price = match_res.iloc[0]['price'] if qua > current_stock: print("out of stock") else: total = current_price * qua print(f"total price = {total}")
核心修改说明
- 输入非法后新增
exit()终止程序,避免后续逻辑报错 - 新增ID存在性校验,匹配不到对应商品时输出
Invalid - 新增库存校验逻辑,购买数量超出库存时输出
out of stock - 修正总价计算逻辑,取匹配ID对应的单个商品单价计算
- 调整输出格式完全匹配需求示例要求
内容的提问来源于stack exchange,提问作者Exclusive
相关产品推荐
相关产品推荐

