Python 如何将列表中的一项弹出为浮点数
我希望这更清楚:Python 如何将列表中的一项弹出为浮点数,python,python-3.x,Python,Python 3.x,我希望这更清楚: numbers = [2, 3, 2] total = 0 while numbers: total += numbers.pop() 这将返回数字的总值 现在,我必须以这种方式(第二种代码)计算购买金额的总价值(第一种代码): 虽然我无法从第一个代码中的输入中获得数字,但每次atempt都会变成一个浮点数,并添加到一个数字中。您的代码有一些问题。主要问题之一是input返回字符串,而不是浮点 您需要从用户处强制转换输入值。标准的做法是这样的 item = input
numbers = [2, 3, 2]
total = 0
while numbers:
total += numbers.pop()
这将返回数字的总值
现在,我必须以这种方式(第二种代码)计算购买金额的总价值(第一种代码):
虽然我无法从第一个代码中的输入中获得数字,但每次atempt都会变成一个浮点数,并添加到一个数字中。您的代码有一些问题。主要问题之一是
input
返回字符串,而不是浮点
您需要从用户处强制转换输入值。标准的做法是这样的
item = input("Enter the price, or type 'done'")
if item == 'done':
... # Likely break from your loop
try:
item = float(item)
except ValueError:
print('Invalid input')
第二个关键问题是,number
是一个列表,您应该使用purchase\u amount
尽管如此,这里不需要从列表中弹出,因为您可以简单地在列表上循环,或者更好地使用sum
这是您的代码的固定版本
固定代码
我没看到这里有什么爆炸,没有。根据这段代码,我必须将购买金额中的itmes作为FLOAD,并将其添加到新代码中。您的答案没有包含足够的信息来重现问题。阅读。我猜在某个时候,您使用了
purchase\u amount.pop
而不是purchase\u amount.pop()
,但是我们需要看到code.subtotal=0,而purchase\u amount:print(purchase\u amount.pop)
item = input("Enter the price, or type 'done'")
if item == 'done':
... # Likely break from your loop
try:
item = float(item)
except ValueError:
print('Invalid input')
purchase_amount = []
while True:
item = input("Enter the price, or type 'done'")
if item == 'done':
break
try:
purchase_amount.append(float(item))
except ValueError:
print('Invalid input')
print(purchase_amount)
total = sum(purchase_amount)
print(total)