【问题标题】:How to write a while loop to input prices and then stops when user inputs 0如何编写一个while循环来输入价格,然后在用户输入0时停止
【发布时间】:2020-01-15 06:17:56
【问题描述】:

我需要编写一个短代码,用户可以输入购物行程中的价格,当用户输入 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))

当价格

TypeError: 'type' 和 'int' 的实例之间不支持'

【问题讨论】:

  • 不会用勺子喂食.. 但是当用户输入 0 时,您需要在 while 循环中使用 break 来打破循环......然后,您可以打印语句
  • 搜索break的用法并在控制台上尝试一下。我相信你会弄清楚如何在当前问题中使用它
  • 非常感谢您的帮助。因此,当输入 0 时,使用 break 可以让它从 while 循环中继续前进。谢谢大家。
  • price = float 应该是什么意思? float 是一个类型,而不是一个数字。
  • 使用while True: 循环,直到在循环中使用break

标签: python list if-statement input while-loop


【解决方案1】:

欢迎来到 Stack Overflow!

首先,你的错误信息:

while price < 0: TypeError: '<' not supported between instances of 'type' and 'int'

错误的第一部分是告诉您导致问题的代码;编译器不喜欢while price &lt; 0:。为什么不?这是信息的第二点:您无法将typeint 进行比较。所以你的 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 循环怎么样?目前,如果price 小于 0,但您还没有获得价格价值,则您正在进入循环,因此这不起作用。你的while 循环下面还有一个else,但这不是while 循环的工作方式,你想要一个if 语句来代替吗? python tutorial 有很多关于流量控制的信息。

这样的事情怎么样:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多