首页 > 解决方案 > 如何编写一个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' 的实例之间不支持'<'

标签: pythonlistif-statementinputwhile-loop

解决方案


欢迎来到堆栈溢出!

首先,您的错误消息:

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 priceis 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)]

最后我们为用户打印这些。


推荐阅读