哪里将计数器变量放在python循环中?

时间:2018-10-25 23:04:08

标签: python for-loop scope counter

是什么让我无法将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)

如果这个问题是重复的,请不要犹豫地将其标记为

1 个答案:

答案 0 :(得分:0)

如果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)