Python购物清单程序打印输出带多余括号引号如何解决
问题排查与修改方案
问题原因
- 遍历
zip生成的配对对象时,没有对返回的二元元组做拆包操作,你代码里的prices变量实际存储的是完整的(商品名, 价格)元组,直接打印元组会输出Python默认的带括号、引号的元组格式,不符合预期。 - 输出逻辑没有添加预期格式中的
.、- $等格式字符。
修改方法
把最后遍历输出的部分改为拆包元组,再用f-string按预期格式拼接输出即可,修改后的核心代码片段:
zipobj = zip(products, product_price) for i, (product, price) in enumerate(zipobj, start = 1): print(f"{i}. {product} - ${price}")
修改后完整可运行代码
products = [] product_price = [] add_product = input("Would you like to add an item?: ") while add_product == "yes": item = input("Enter the product: ") products.append(item) item_price = input("How much does this item cost? ") product_price.append(item_price) print(f"{item} has been added to the cart. ") add_product = input("Would you like to add an item? ") print("The contents of the shopping cart are: ") zipobj = zip(products, product_price) for i, (product, price) in enumerate(zipobj, start = 1): print(f"{i}. {product} - ${price}")
内容的提问来源于stack exchange,提问作者Kudos
相关产品推荐
相关产品推荐

