gpt4 book ai didi

python - 如何在 python 中获取小数点后超过 2 位的价格的 ItemException ex) $4.456

转载 作者:行者123 更新时间:2023-12-01 02:51:44 25 4
gpt4 key购买 nike

class Item:
def __init__(self, name, id, price):
self.name = name
self.id = id
self.price = price

def getName(self):
return self.name
def getId(self):
return self.id
def getPrice(self):
return self.price

def __str__(self):
return str(self.name) + " " + str(self.id) + " " + str(self.price)

class Shipment:
def __init__(self, id):
self.id = id
self.items = []

def getId(self):
return self.id
def getItems(self):
return self.items

def addItem(self, Item):
self.items.append(Item)

def __str__(self):
if self.items == []:
return str(self.id) + ": []"
else:
returnvalue = str(self.id) + ": ["
ctr = 0
while ctr < len(self.items) - 1:
returnvalue += str(self.items[ctr]) + ","
ctr += 1
returnvalue += str(self.items[len(self.items) - 1])
return returnvalue + "]"

class ItemException:
def __init__(self, message):
self.message = message
self.items = []

def __str__(self):
return str(self.message)

def main(list):

shipment = []
ctr = 0
while ctr < len(list):
list[ctr] = list[ctr].replace("\n" , "")
ctr += 1

ctr2 = 0
while ctr2 < len(list):
if list[ctr2].isdigit():
ship = Shipment(list[ctr2])
shipment.append(ship)
else:
split = list[ctr2].split()
if "$" not in list[ctr2]:
if len(split) != 2:
raise ItemException("Invalid name")
if "-" in list[ctr2]:
raise ItemException("Price can't be negative")
if ((len(split)) != 1):
if ctr2 != len(list):
item = Item(split[0], split[1], list[ctr2 + 1])
ship.addItem(item)
temp = list[ctr2].count(".")
if temp > 1:
raise ItemException("Invalid price, more than one .")

#need to add exception for more than 2 digits past the decimal point
ctr2 += 1

return shipment

如果价格“$4.567\n”中的小数点后位数超过 2 位,我需要弄清楚如何引发此测试的异常:

def test16():

result = False
try:
main(['55555555\n','socks 12345\n','$4.567\n','socks 12345\n','$4.56\n'])
except ItemException:
result = True
print result
return result

我认为我需要将其拆分,但我不确定如何仅隔离价格,然后将其拆分以获取小数点后的数字。一旦我到达这一点,我想如果 cents > 2 引发 ItemException 我可以做。

最佳答案

你的分割是对的。您可以尝试:

>>> '$4.587'.split('.')
['$4', '568']
>>> len('$4.587'.split('.')[1]) > 2
True

第二个条件检查点后的位数是否大于 2。

关于python - 如何在 python 中获取小数点后超过 2 位的价格的 ItemException ex) $4.456,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44688869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com