python - 如何编写一个while循环来输入价格,然后在用户输入0时停止
问题描述
我需要编写一个短代码,用户可以输入购物之旅的价格,当用户输入 0 时,while 循环将停止。在它停止之后,我需要一个 else 语句来显示商品总数、平均价格和总价。
我是编程新手,我从 python 开始。请让我知道我做错了什么。
price = float
items = float
while price < 0:
items = price
price = input("Please enter prices of items:")
else:
avg = float(sum(items) / len(items))
print('Number of items purchased:', len(items))
print('Average price of items: $', avg)
print('Total price of purchased items: $', sum(items))
当价格 < 0 时:
TypeError: 'type' 和 'int' 的实例之间不支持'<'
解决方案
欢迎来到堆栈溢出!
首先,您的错误消息:
while price < 0: TypeError: '<' not supported between instances of 'type' and 'int'
错误的第一部分是告诉您导致问题的代码;编译器不喜欢while price < 0:
. 为什么不?这是信息的第二点:你不能将 atype
与 a 进行比较int
。因此,您的price
变量是一种类型,而不是听起来不正确的数字(int 或 float)。
那么我们如何在python中正确声明变量呢?我们不需要明确告诉解释器它们是什么类型的变量,它会自己解决。例如,这些是所有工作的不同变量声明:
price = 0.123 // this declares a float
name = 'BoatingPuppy' // this declares a string
favourites = ['apples','pears','diamonds'] // and this declares a list
它们都可以工作,而price = float
不是声明一个新的浮点变量。
现在你的while循环怎么样?目前你正在进入你的循环 if price
is less than 0 但你还没有得到价格的价值,所以这是行不通的。你的循环else
下面也有一个while
,但这不是while
循环的工作方式,你想要一个if
声明吗?python 教程有很多关于流控制的信息。
像这样的东西怎么样:
prices = []
while True:
price = float(input('Enter price of '+item+': ')
if price = 0:
break
else:
prices.append(price)
total_price = prices.sum()
avg_price = total_price/len(prices)
print('Total price: ', end='')
print(total_price)
print('Average price: ', end='')
print(avg_price)]
让我们来看看它在做什么。
prices = []
首先,我们制作了一个空列表来存储所有价格。
while True:
price = float(input('Enter price of '+item+': ')
if price = 0:
break
else:
prices.append(price)
接下来我们使用while
循环。While 循环在之后评估语句while
以确定它是否应该运行,因此如果我们将其设置为,True
那么它将永远运行(或直到我们break
退出它)。
每次while
循环运行时,它都会向用户询问价格,使用if
语句检查价格是否为 0,如果是则跳出while
循环,如果不是则将值添加到列表prices
中。
total_price = prices.sum()
avg_price = total_price/len(prices)
接下来我们计算prices
列表中所有项目的总价格,并使用它通过将总价格除以列表中的项目数来计算平均价格。
print('Total price: ', end='')
print(total_price)
print('Average price: ', end='')
print(avg_price)]
最后我们为用户打印这些。
推荐阅读
- activemq-artemis - 无法在 3 HA 集群架构上使用相同的 clientId
- performance - UWP TreeView UI 死锁 - 加载时间从不到 1 秒到超过 10 秒 - 首次运行针对新运行
- excel - 在 VBA 中为 PDF 设置的复选框未保持选中状态
- regex - 正则表达式意外行为记事本++
- python - standard_init_linux.go:211:exec 用户进程导致“没有这样的文件或目录”?
- python - 合并来自两个不同文件夹的两个图像(python)
- javascript - 用javascript生成模态
- anaconda - OSError: 找不到 lib geos_c.dll 或加载它的任何变体 ['..\Library\\lib\\geos_c.dll']
- go - 如何将内部包与 go 模块一起使用?
- python - 有没有办法验证作为参数传递的 lambda 函数只分配 True 或 False?