字典定价for循环遇无效输入不重试的问题修复咨询
修复菜单定价循环的问题
你的问题出在createPrice函数的for循环逻辑里:当输入无效价格时,continue只会跳过当前迭代的剩余代码,直接进入下一个菜品的价格输入,不会重复当前菜品的输入步骤。下面是两种简单的修复方法:
方法1:为每个菜品的价格输入添加内部while循环
给每个菜品单独套一个循环,直到输入有效的价格才进入下一个菜品。修改后的代码如下:
def createPrice(menu): for k in menu: while True: userPrice = input(f"Enter price for {k}:\n") if userPrice.isdecimal(): menu[k] = float(userPrice) break # 输入有效,跳出内部循环,处理下一个菜品 else: print("Enter a valid value!") return menu
这个逻辑很直观:对每个菜品,反复要求输入价格,直到用户输入符合要求的纯数字,才切换到下一个菜品。
方法2:用while循环遍历菜单键(替代for循环)
通过迭代器控制遍历过程,当输入无效时不推进迭代,继续处理当前菜品:
def createPrice(menu): menu_items = iter(menu.keys()) current_item = next(menu_items) while True: userPrice = input(f"Enter price for {current_item}:\n") if userPrice.isdecimal(): menu[current_item] = float(userPrice) try: current_item = next(menu_items) except StopIteration: break # 所有菜品处理完,退出循环 else: print("Enter a valid value!") return menu
这种方式用迭代器逐个获取菜品,只有输入有效时才获取下一个菜品,无效则保持当前菜品继续输入。
另外注意你createMenu函数里的一个小问题:代码里用了newMenu但参数是menu,应该改成len(menu) + 1,避免变量未定义的错误。
内容的提问来源于stack exchange,提问作者mistermatt
相关产品推荐
相关产品推荐

