Python预算购车逻辑异常求助:预算判断错误问题排查
问题排查与修正方案
错误核心原因
你误将最低价格在列表中的索引值当作最低价格本身来和预算做比较:
bikeCatalogList.index(min(bikeCatalogList))返回的是最低价格元素在列表中的位置(这里最低价格375对应索引0)- 当预算设为1时,判断条件
budget > lowestBikePrice实际是1 > 0,条件成立,因此错误输出了购买提示。
修正后的代码
budget = 1 bikeUnivega = 375 bikeKalkhoff = 449 bikeFocus = 462 bikeCatalogList = (bikeUnivega, bikeKalkhoff, bikeFocus) lowestBikePrice = min(bikeCatalogList) # 直接获取实际最低价格数值 if budget >= lowestBikePrice: # 预算等于最低价格时也能购买,用>=更合理 print(f'I Will buy the bike for the lowest price of {lowestBikePrice} EUR.') else: print('I dont have enough money for the bike. I will save money until next year.')
关键修正点
- 直接用
min(bikeCatalogList)获取最低价格的数值,而非索引 - 将判断条件改为
budget >= lowestBikePrice,覆盖预算刚好等于最低价格的场景
内容的提问来源于stack exchange,提问作者Dexas
相关产品推荐
相关产品推荐

