【问题标题】:why doesn't loop break at 0 count when I set while var != 0为什么当我设置 while var != 0 时循环不会在 0 计数处中断
【发布时间】:2019-09-20 04:45:28
【问题描述】:

我正在为我的班级编写一个程序,该程序是输入您要在线购买的商品,然后输入价格。我创建了一个 while 循环,一旦用户购买的物品总数变为零,它就会中断,这样我就可以接收他们想要的所有物品。出于某种原因,尽管当变量 totalItems 达到零时(我知道这是因为我将每一行都打印出来)循环并没有中断,实际上它一直处于负数。

def main():
    totalItems = int(input('How many items are you buying? '))
    while totalItems != 0:
        item1 = input('What is the first item? ')
        cost1 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item2 = input('What is the second item? ')
        cost2 = input('What is the price of the second item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item3 = input('What is the third item? ')
        cost3 = input('What is the price of the third item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item4 = input('What is the fourth item? ')
        cost4 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item5 = input('What is the first item? ')
        cost5 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
    print('done')


main()

【问题讨论】:

  • 如果totalItems 低于 0 会怎样?

标签: python while-loop


【解决方案1】:

循环条件仅在所有其中的代码运行后检查。而且由于它在那里减少了五次,它很有可能从 2 变为 -3,并且它们都不等于 0,所以它会继续。

此外,您在那里有五倍多或少相同的代码。为什么?只需确保它存在一次即可。

而守卫应该是while totalItems > 0:,只是一些防御性编程以确保循环结束,即使错误导致变量低于0。

最后,不要有变量“cost1”、“cost2”、“cost3”等等,尤其是如果您事先不知道需要多少变量。这就是列表的用途。

【讨论】:

    【解决方案2】:

    您在循环中多次递减变量。

    【讨论】:

      【解决方案3】:

      循环将遍历它的整个主体,并且在执行完整个主体之后第二次检查条件:

      while thing:
          do_stuff()
          thing = 0
          hello()  # this is still executed, even though `thing == 0`
          what()  # and this too
      

      看起来您想在totalItems 变为零时自动退出循环循环中的任何位置,但循环不会这样做,您必须手动完成:

      while totalItems != 0:
          item1 = input("What's the first item?")  # mind the quotes here
          cost1 = input('What is the price of the first item? ')
          totalItems = totalItems - 1
          if totalItems == 0:
              break  # get out of the loop
          print(totalItems)
      
          item2 = input("What's the second item?")  # mind the quotes here
          cost2 = input("What is the price of the second item?")  # mind the quotes here
          totalItems = totalItems - 1
          if totalItems == 0:
              break  # get out of the loop
          print(totalItems)
      
          # and so on
      

      【讨论】:

        【解决方案4】:

        Python 的真值表:“任何非零数都是真值”。这意味着while totalItems: 很好。

        for 循环可能更适合您的需求。

        for item_counter in range(total_items): # do stuff
        

        一旦您从 0 变为 total_items,这将停止。这样做的好处是不需要自己跟踪所有内容。

        您可以格式化要打印给用户的字符串。

        item = input('Item {}: '.format(item_counter))  # Item 1:
        cost = input('How much did {} cost? '.format(item))  # How much did The Internet cost?
        

        如果您希望为“第一个”、“第二个”、“第三个”等项目提供一些巧妙的东西,您需要映射它们,但由于这需要无限量的输入,因此给出数字表示通常更容易。 101,102,103,104,105,106,107,108,109,110,111,112,113,220,330,440,550,660,770,880,990 而你只完成了第 111 十亿个(ish)项目。


        扩展字典dict 您还可以将项目分配到字典中。

        products = dict{}
        for loop:
          item = ...
          if item not in products:
            cost = ...
            product[item] = cost
        

        这将做的是保存具有无转基因认证有机无添加糖无反式脂肪饮食水价格的项目,因此如果用户需要该项目的多个副本,他们只需添加一次成本。对此进行扩展,您可以计算该项目的添加次数。

        ...
              product[item] = [cost, 1]
            else:
              product[item][1] += 1
        

        product[item] 指的是列表 [cost, count] 的值。我们需要修改第二个索引,因此我们指定 [1],因为我们从 0 开始计数。最终结果看起来有点混乱,但最终我们也会跟踪添加了多少重复项。

        【讨论】:

          【解决方案5】:

          在这种情况下,我会使用for-loop:

          • while-loop 更适合连续运行,直到出现给定条件。
          • for-loop 更适合循环使用 rangelist 的值。
          • 无需对每个项目进行硬编码。如果有 100 个项目怎么办?
          • 代码中的while-loop 不起作用,因为python 是顺序的,并且代码的顺序是从item1item5while != 0: 直到 cost5 之后才会再次评估。
            • 此外,如果totalItems 的初始值为<= 3,则totalItems 在重新评估while 条件之前将是< 0。在这种情况下,循环将永远持续下去。
          • 尽可能重复使用代码
          • product & cost 现在位于函数返回的 dict
          def main():
              totalItems = int(input('How many items are you buying? '))
              item_dict = dict()
              for item in range(1, totalItems + 1):
                  product = input(f'What is item {item}? ')
                  cost = input(f'What is the price of item {item}? ')
                  item_dict[f'item_{item}'] = {'product': product, 'cost': cost}
              print('done')
              return item_dict
          
          items = main()
          

          输出:

          How many items are you buying?  4
          What is item 1?  Book
          What is the price of item 1?  7.50
          What is item 2?  Car
          What is the price of item 2?  15000
          What is item 3?  Milk
          What is the price of item 3?  6.99
          What is item 4?  Coffee
          What is the price of item 4?  4.99
          done
          

          存储items:

          print(items)
          

          输出:

          {'item_1': {'product': 'Book', 'cost': '7.50'},
           'item_2': {'product': 'Car', 'cost': '15000'},
           'item_3': {'product': 'Milk', 'cost': '6.99'},
           'item_4': {'product': 'Coffee', 'cost': '4.99'}}
          

          【讨论】:

            猜你喜欢
            • 2020-07-17
            • 1970-01-01
            • 2022-11-21
            • 1970-01-01
            • 2021-04-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-03-01
            相关资源
            最近更新 更多