2 代码部分连接和列表中字母的注册

2 code parts connection and register of letters in list

我正在为 运行 购物程序编写代码,您可以在其中编写需要购买的产品并将其添加到购物车,总费用将显示在购物车中。我还编写了一个代码,以便在总成本接近预算边界(70% 或更多)时发出预算警告。

我想连接这两部分代码以便它们一起工作,而且我想确保无论寄存器如何都计算输入的产品(所以不管它是否 'Sause' 或 'SAUSe' 输入)

非常感谢您的帮助!

#PRODUCT CART

productlist = ['Sushi', 'Spirulini', 'Sause', 'Cabbage']
pricelist = [56, 31, 4, 9]
totalcost = 0
inpt = input('Add to cart: ')
#indx = productlist.index(inpt)
#price = pricelist[indx]
endWord = 'stop'
spacing = ''

while inpt.lower() != endWord.lower():

  if inpt not in productlist and len(inpt) > 0:
    print("\nProduct is not found, try again")
    inpt = input('\nAdd to cart: ')
  
  elif inpt in productlist:
    indx = productlist.index(inpt)
    price = pricelist[indx]
    totalcost += price
    print("\n{} costs {:d} usd".format(inpt, price))
    print (f'Total cost is {totalcost}')
    inpt = input('\nAdd to cart: ')

  elif spacing in inpt:
    inpt = input('\nAdd to cart: ')

print ('\nThank you for using ShopCart.com!')

#BUDGET WARNINGS

#budget = 150 #actually, it is better to make it as input

#moreThan70Line = int(totalcost / budget * 100)

#if totalcost >= (70/100 * budget) and totalcost < budget:
#  print (f'Look out, you are on the {moreThan70Line}% of your budget')
  
#elif totalcost >= budget:
#  print (f'Seems like you used {moreThan70Line}% of #your today\'s budget')

您可以使用 check_budget 功能在用户将商品添加到购物车时检查并提醒他们。

# BUDGET WARNINGS

def check_budget(total_cost, budget):
    percentage_used = int(totalcost / budget * 100)
    if percentage_used >= 70 and total_cost < budget:
        print(f'Look out, you are on the {percentage_used}% of your budget')
    elif total_cost >= budget:
        print(f'Seems like you used {percentage_used}% of #your today\'s budget')

这样您就可以在您的产品购物车代码中使用辅助函数 check_budget,类似于这样。

此外,您可以将 productlist 中的项目保留为小写并将您的用户输入转换为小写,以实现您的产品不区分大小写。

# PRODUCT CART

productlist = ['Sushi', 'Spirulini', 'Sause', 'Cabbage']
pricelist = [56, 31, 4, 9]
totalcost = 0
inpt = input('Add to cart: ')
endWord = 'stop'
spacing = ''
budget = int(input('\nEnter budget: '))

while inpt.lower() != endWord.lower():
    inpt = inpt.lower()
    if inpt not in productlist and len(inpt) > 0:
        print("\nProduct is not found, try again")
        inpt = input('\nAdd to cart: ')

    elif inpt in productlist:
        indx = productlist.index(inpt)
        price = pricelist[indx]
        totalcost += price
        print("\n{} costs {:d} usd".format(inpt, price))
        print (f'Total cost is {totalcost}')
    
        # budget check and alert
        check_budget(totalcost, budget)
        
        inpt = input('\nAdd to cart: ')
    
    elif spacing in inpt:
        inpt = input('\nAdd to cart: ')

print ('\nThank you for using ShopCart.com!')