Python如何持续询问用户输入并计算录入商品价格总和
问题说明
需要实现的效果:持续询问用户是否添加商品价格,用户答复no时,输出所有已录入商品的总价格。
现有代码问题:仅完成第一次询问后就终止运行,无法支持第二次及后续的商品价格录入,原代码如下:
price = 0 user = input ("Do you want to continue (yes/no):") if user == "yes": for x in range(0,1): price = int( input("Please enter the price of the product" + str(x) + ":")) print(price) elif user == "no": print("Your total price is: " + price)
原代码错误点
- 无外层常驻循环结构,仅做一次分支判断就会执行完流程退出,无法重复触发询问
- 内层
for x in range(0,1)固定只循环1次,进入yes分支也只能录入1件商品 - 价格计算逻辑错误,每次输入价格直接覆盖
price变量值,没有做累加,无法得到正确总价 - 输出总价时直接拼接整数和字符串,运行时会触发类型错误
- 所有交互提示为英文,未按要求翻译为中文
修复后可用代码
所有交互提示已翻译为中文,修复全部逻辑问题,支持任意次商品录入:
total_price = 0 product_index = 0 while True: user_choice = input("是否需要继续添加商品价格(yes/no):") if user_choice == "no": break elif user_choice == "yes": current_price = int(input(f"请输入第{product_index + 1}件商品的价格:")) total_price += current_price product_index += 1 else: print("输入无效,请输入yes或no") print(f"所有已录入商品的总价格为:{total_price}")
实现逻辑说明
- 用
while True构建无限循环,用户输入no前会持续运行,支持不限次数的商品录入 - 单独用
total_price变量存储累计总价,每次录入新商品价格时做累加计算,不会覆盖历史数据 - 增加非法输入校验,用户输入非yes/no内容时会提示重新输入,不会直接崩溃
- 所有交互文案均为中文,符合使用要求
内容的提问来源于stack exchange,提问作者David Lopez
相关产品推荐
相关产品推荐

