【问题标题】:Can't reset index for loop in Python无法在 Python 中为循环重置索引
【发布时间】:2017-11-03 16:38:30
【问题描述】:

我想创建一个可用于 ATM 的程序。这是我做的:

# 500, 20, 100, 50, 10, 5, 1
nrb = 0
i=0
j=0
bancnote = [500, 200, 100, 50, 10, 5, 1]
for i in range(7):
    print('b:',bancnote[i])
suma = int(input('Scrieti suma dorita: '))
while suma > 0:
    while j <= 6:
        if suma >= bancnote[j]:
            nrb +=1
            suma -=bancnote[j]
            print('Am scazut: ', bancnote[j])
            print('Ramas: ',suma)
            print("Bancnote: ",nrb)
            j=0

无法重置该循环的计数器。我能做什么?

【问题讨论】:

  • 请张贴代码而不是图片,以便其他人复制并寻求解决方案。
  • 您的代码应以文本而非图像的形式提供,以便我们重现您的问题
  • 把代码放在这里,让我们知道究竟是哪个循环导致了问题..
  • 这是代码:#bancomat cu bancnote de:# 500, 20, 100, 50, 10, 5, 1 nrb = 0 i=0 j=0 bancnote = [500, 200, 100, 50, 10, 5, 1] for i in range(7): print('b:',bancnote[i]) suma = int(input('Scrieti suma dorita: ')) while suma &gt; 0: while j &lt;= 6: if suma &gt;= bancnote[j]: nrb +=1 suma -=bancnote[j] print('Am scazut: ', bancnote[j]) print('Ramas: ',suma) print("Bancnote: ",nrb) j=0
  • 抱歉文本格式化...

标签: python loops counter reset


【解决方案1】:

(对我来说更容易理解代码,因为我也可以阅读语言)

您忘记了增加j,因此您的代码每次只会查看 500 钞票。因此,不要试图从总和中减少其他值。

【讨论】:

    【解决方案2】:

    变量 j 没有增量。所以循环将保持原样

    【讨论】:

      【解决方案3】:

      Python 并不真正需要您的索引。 考虑到我对问题的理解,代码应该类似于:

      note_values = (500, 200, 100, 50, 10, 5, 1)
      
      def partition(value):
          result = []
          for note in note_values:
              whole, value = divmod(value, note)
              result.append(whole)
          return result
      
      if __name__ == "__main__":
          value = int(input("Sum wanted: "))
          notes = partition(value)
          for number, value in zip(notes, note_values):
              if number != 0:
                  print("{} note of {:3d}".format(number, value))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        相关资源
        最近更新 更多