是什么让我无法将evenCounter
或'oddCounter'变量放入for循环或if语句中?如果计数器不在循环范围内,则循环如何知道计数器在哪里?
list1 = [1,2,3,4,5,6,7,8]
evenCounter = 0
oddCounter = 0
for i in list1:
if i%2 == 0:
evenCounter += 1
else:
oddCounter += 1
print(evenCounter)
print(oddCounter)
如果这个问题是重复的,请不要犹豫地将其标记为
最佳答案
如果counter
在循环中,则在您遍历序列时,它会继续重新启动。下面的loopCounter
被添加到if-else
循环中,但是每次迭代时都将其重置为零,在本示例中,您可以使用print
看到它
list1 = [1,2,3,4,5,6,7,8]
evenCounter = 0
oddCounter = 0
for i in list1:
loopCounter = 0
print(loopCounter)
if i%2 == 0:
evenCounter += 1
loopCounter += 1
else:
oddCounter += 1
loopCounter += 1
print(evenCounter)
print(oddCounter)