购物清单程序功能实现及代码逻辑完善技术问询
购物清单程序开发解决方案
嘿,我来帮你搞定这个购物清单程序!先明确下核心需求:程序要持续提示用户输入购物条目,当输入0时终止输入流程,最后把所有收集到的条目整理打印出来。
先看看你提供的待完善代码,这里面逻辑有点偏差哦——原来的代码判断输入是纯字母就终止循环,这和我们需要的输入'0'才终止的规则完全不符,而且还没法处理带空格的条目(比如cucumber water),因为isalpha()遇到空格会直接返回False。
修正后的完整代码
# 初始化空列表存储购物条目 shopping_list = [] while True: item = input("Add new item to shopping list: ") # 触发终止条件:输入为'0'时跳出循环 if item == '0': break # 过滤空输入(避免用户只按回车添加空条目) if item.strip(): shopping_list.append(item) # 打印最终购物清单 if shopping_list: print(f"Items on your shopping list are: {', '.join(shopping_list)}") else: print("Your shopping list is empty!")
代码逻辑说明
- 先创建空列表
shopping_list,用来保存用户输入的所有有效条目; while True构建无限循环,直到用户输入0时通过break终止流程;- 加入
item.strip()的判断,过滤掉用户误输入的空内容,让程序更健壮; - 最后用
', '.join(shopping_list)把列表条目拼接成符合示例的字符串格式,清单为空时还会给出友好提示。
测试交互示例
Add new item to shopping list: mango
Add new item to shopping list: cucumber water
Add new item to shopping list: pineapple
Add new item to shopping list: beef
Add new item to shopping list: 0
Items on your shopping list are: mango, cucumber water, pineapple, beef
这样就完全匹配你的需求啦!
内容的提问来源于stack exchange,提问作者nik
相关产品推荐
相关产品推荐

