我该如何求和?

-4 投票
1 回答
76 浏览
提问于 2025-04-13 02:31

我想把两个或更多的项目加起来,但我搞不清楚怎么做。代码如下:

User = input('I would like to buy ')
  List.append(User)
  User1 = input('Would you like to see your list? > ')  
  while 'no' in User: 
    User = input('I would like to buy ' )
    List.append(User)
    User1 = input('Would you like to see your list? > ')
  if 'yes' in User:
    Check_List()
    print('\n\n', 'Do you want to buy the current items in your shopping list?')
    User2 = input('> ')
    if 'yes' in User2:
      print('\n\n', 'Your total is')
    if 'no' in User1:
      Repeat()
  if 'no' in User:

不过,重点在这段代码:

 try:
          idx = Products.index(User) 
          price = Prices[idx]
          
          print('\n\n','Your item/s total is {:d}'.format(price))
      except ValueError:
          print('This item is not in the shop try a different item.')

我试着用sum()函数,或者把它放进一个范围里,但都没成功。只要能把所有东西加起来,不用改太多代码,我就满意了。我知道我的代码可以更优化,但我想按照我自己的方式来做,我只是需要在这方面的帮助。

1 个回答

0

看起来你想要递归地计算价格的总和,但有两个问题。

  1. 每次你调用你的重复函数时,价格都是当前项目的价格,而不是总价格。
  2. 没有任何代码在计算价格的总和。

你可以在Repeat函数外面先把价格初始化为0,然后把你的代码改成这样:

price = 0
def Repeat()
# your code
   try:
          idx = Products.index(User) 
          price += Prices[idx]
          
          print('\n\n','Your item/s total is {:d}'.format(price))

在这种情况下,确保当用户更改时把价格重置为0。

另一种方法是使用记忆化技术。

def Repeat(price = 0)
# your code
try:
          idx = Products.index(User) 
          price += Prices[idx]
          
          print('\n\n','Your item/s total is {:d}'.format(price))
# rest of your code
    if 'no' in User1:
      Repeat(price)
  if 'no' in User:

撰写回答