python计算失败

2024-03-29 06:39:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在为学校做一个项目,我们必须建立一个收据,我的循环是时髦的,没有给我一个正确的计算。另外,我很难计算出购买100英镑要打10%的折扣和8%的销售税

itemName = ""
itemQuantity = ""
itemPrice = ""
moreItems = "Yes"
userResponse = ""
itemsPurchased = 0.0 # additional items purchased

itemName = input ('Please enter the name of the item: ')
itemQuantity = float(input ('Please enter the number items choosen: '))
itemPrice = float(input('Please enter item price: '))

while moreItems == "Yes":
    itemName = input ( ' Please enter the name of the item: ')
    itemsPurchased = float(input("Please enter the number of items puchased: "))
    itemPrice = float(input("Please enter item price: "))
    itemsPurchased +=1
    itemPrice +=1
    userResponse =input("Please enter Y or y if you have more items items to enter: ")
    if userResponse == " Y " or userResponse == "y":
        moreItems = "Yes"
    else:
        moreItems = "No"

total = (itemQuantity * itemPrice ) 

print (" item price: " + str  (total))

if total >= 100:
    print (total*.10  + total)
else:
    print(str(total))

******我是个初学者,所以请对我保持简单


Tags: theinputitemsfloatitemyestotalenter
1条回答
网友
1楼 · 发布于 2024-03-29 06:39:30

你可以尝试一种面向对象的方法。这样你会有一个更好的概述,更容易扩展代码

Object-orientation对于初学者来说并不像函数式编程那样直观,但是当程序增长时,它会给您带来很大的好处

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


class Order:
    def __init__(self):
        self.positions = []

    def get_price(self):
        return sum([position.get_price() for position in self.positions])

class OrderPosition:
    def __init__(self, item_obj, quantity):
        self.item = item_obj
        self.quantity = quantity

    def get_price(self):
        return self.item.price * self.quantity

order = Order()
moreItems = True
while moreItems:
    itemName = input ( ' Please enter the name of the item: ')
    itemsPurchased = float(input("Please enter the number of items puchased: "))
    itemPrice = float(input("Please enter item price: "))
    item = Item(itemName, itemPrice)
    order.positions.append(OrderPosition(item, itemsPurchased))

    input_text = "Please enter Y or y if you have more items items to enter: "
    moreItems = input(input_text).lower() == 'y'

total = order.get_price()
print('Item price (without tax): ' + '${:,.2f}'.format(total))
if total >= 100:
    total -= total * 0.1
inclusive_tax = total * 1.08
print('Item price (with tax): ' + '${:,.2f}'.format(inclusive_tax))

相关问题 更多 >