Python求和报错求助:新手编写商品总价计算代码遇问题
问题分析与解决方向
你的代码主要有两个核心问题导致求和失败:
- 变量覆盖问题:
sum_变量在每次while循环里都会被新输入的商品价格替换,根本没保存之前输入的价格,自然没法累积求和。 - sum()函数用法错误:Python的
sum()函数需要传入可迭代对象(比如列表、元组这类包含多个元素的集合),你直接传单个整数sum_会触发报错,因为整数不是可迭代的。
两种修正方案(适合新手理解)
方案1:用累加变量逐步计算总价
初始化一个总价变量,每次输入商品价格后,把价格加到这个变量里,循环结束后再打印总价:
number_of_items = int(input('How many items do you have: ')) x = 0 total = 0 # 初始化总价变量 if number_of_items == 0: print('Are you not buying anything? ') elif number_of_items > 10: print('Sorry we only accept 10 items or less') else: while x < number_of_items: x += 1 price = int(input(f'Cost of item {x}: ')) total += price # 把当前价格加到总价里 print(f'Total cost: {total}') # 循环结束后打印总价
方案2:用列表存储所有价格,最后用sum()求和
先把所有输入的价格存到列表里,循环结束后用sum()计算列表的总和:
number_of_items = int(input('How many items do you have: ')) x = 0 prices = [] # 初始化空列表存储价格 if number_of_items == 0: print('Are you not buying anything? ') elif number_of_items > 10: print('Sorry we only accept 10 items or less') else: while x < number_of_items: x += 1 price = int(input(f'Cost of item {x}: ')) prices.append(price) # 将价格添加到列表 total = sum(prices) # 用sum()计算列表所有元素的和 print(f'Total cost: {total}')
另外注意你的原代码里elif number_of_items > 10:下面的print语句没有缩进,这会触发语法错误,修正后的代码已经补上了缩进。
内容的提问来源于stack exchange,提问作者Billy Whitley
相关产品推荐
相关产品推荐

