如何通过 Python 制作账单

How to make a bill by Python

我是大一新生,我想做一个账单,上面写明我买了什么,数量,总共花了多少钱。

customer = str(input("Customer's name: "))
print ("Welcome to our store")
print ("This is our products")
print ("orange 0.5$)
print ("Apple 1$)
print ("Grape 0.5$)
print ("Banana 0.5$)
chooseproducts= int(input("What do you want to buy: "))

For output example. Can you guys help me please. 
    

         BILL
Orange     5    2.5$
Apple      3    3$
Grape      2    1$
Total:     10   6.5$

首先,您的 str(input(customer's name: )) 代码需要更改。 input()调用需要一个字符串作为问题,而且撇号有Python认为是字符串的开始。 此外,当您打印成本时,您需要另一个右引号。当您询问用户他们想买什么时,我想您希望他们输入水果的名称。由于前面有 int(),因此 Python 无法将“orange”或“grape”等字符串转换为整数。然而,当人们想买多件东西时,他们可能只会放一件东西。 我想这不是您的全部代码,您还有计算成本的部分。如果让我来写这段代码,我会这样写:

customer = str(input("Customer's Name:"))
print ("Welcome to our store")
print ("This is our products")
print ("Orange 0.5$")
print ("Apple 1$")
print ("Grape 0.5$")
print ("Banana 0.5$")
prices = {"orange":0.5,"apple":1,"grape":0.5,"banana":0.5}# I added this so we can access the prices later on
#chooseproducts= int(input("What do you want to buy: "))
# The code below this is what I added to calculate the cost.
productnum = input("How many things do you want to buy: ") # This is for finding the number of different fruits the buyer wants
while not productnum.isdigit():
    productnum = input("How many different products do you want to buy: ")
productnum = int(productnum)
totalprice = 0
totalfruit = 0
print('         BILL')
for i in range(productnum):
    chosenproduct = input("What do you want to buy: ").lower()
    while not chosenproduct in ['orange','apple','banana','grape']:
        chosenproduct = input("What do you want to buy: ").lower()
    fruitnum = input("How many of that do you want to buy: ")
    while not fruitnum.isdigit():
        fruitnum = input("How many of that do you want to buy: ")
    fruitnum = int(fruitnum)
    totalfruit += fruitnum
    price = fruitnum * prices[chosenproduct]
    totalprice += price
    startspaces = ' ' * (11 - len(chosenproduct))
    endspaces = ' ' * (5 - len(str(fruitnum)))
    print(chosenproduct.capitalize() + startspaces + str(fruitnum) + endspaces + str(price) + '$')

print('Total:     ' + str(totalfruit) + ' ' * (5 - len(str(totalprice))) + str(totalprice) + '$')

复制前请确保您理解代码,谢谢!