无法在 Python 中重置循环索引
Can't reset index for loop in Python
我想创建一个可用于 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
我无法重置该循环的计数器。我能做什么?
(我看懂了语言,所以更容易看懂代码)
你忘记的是递增j
,所以你的代码每次只会看500的钞票。因此不会试图从总和中减少其他值。
变量 j
没有增加。所以循环将保持原样
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))
我想创建一个可用于 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
我无法重置该循环的计数器。我能做什么?
(我看懂了语言,所以更容易看懂代码)
你忘记的是递增j
,所以你的代码每次只会看500的钞票。因此不会试图从总和中减少其他值。
变量 j
没有增加。所以循环将保持原样
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))