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

Python循环输出异常:修复商品价格查询功能及规范循环break用法

代码问题修复

现有代码存在两处核心逻辑错误:

  1. for循环的else分支错误添加了break,导致循环只会执行1次就终止:如果输入的商品不是列表第一个元素,第一次判断不匹配就直接跳出循环,永远匹配不到后面的商品
  2. 「商品不存在」的提示没有做条件判断,不管有没有找到匹配的商品,循环结束后都会执行,所以就算找到商品输出价格后,还会多输出一行不存在的提示

修复后的代码如下:

def salestracker():
  print("---Sales Tracker---")
  print("---MENU---")
  print("""
  1. Find the price of an item
  2. Enter sales of an item
  3. Find total of the day
  
  """)
  
  items=["Chicken Wings","Jollof Rice", "Thai fried rice", "Dumplings"]
  price=[5,7,8,5]
  findprice(items,price)


def findprice(items,price):
  print("---Find Price---")
  item=input("Enter Item:")
  for i in range(len(items)):
    if item==items[i]:
      print(price[i])
      break
  else:
    # 只有for循环没有被break打断,也就是遍历完所有元素都没找到匹配时才执行
    print("There is no such item")
salestracker()

如果觉得for...else语法不好理解,也可以用标记变量的写法,可读性更高:

def findprice(items,price):
  print("---Find Price---")
  item=input("Enter Item:")
  found = False
  for i in range(len(items)):
    if item==items[i]:
      print(price[i])
      found = True
      break
  if not found:
    print("There is no such item")
for循环搭配break的最佳实践
  • 只有确认达到循环终止目标时才使用break:比如匹配类场景下,只有找到目标元素的分支才加break,不匹配的场景不要随意加break,避免提前终止遍历
  • 区分两种循环结束场景:Python原生支持for...else语法,else块的代码只会在循环完整遍历完所有元素、没有被break打断时执行,非常适合匹配、查找类的循环场景
  • 复杂逻辑优先用标记变量:如果循环内判断逻辑较多,建议提前声明标记变量(比如found、finished),满足条件时修改标记变量状态后再break,循环结束后通过标记变量判断后续逻辑,代码可读性更强,也不容易出现分支错误
  • 不要在嵌套循环里滥用break:break只能跳出当前层级的循环,如果需要跳出多层循环,建议用标记变量或者封装成函数用return返回,多层break容易出现逻辑漏洞

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:06:04