1) with "range" in for loop (with wrong output)
n=[3,5,1,0,2]
even_count, odd_count = 0,0
for i in range(0,len(n)):
if (i%2==0):
even_count =1
else:
odd_count =1
print("total even nos. are:",even_count)
print("total odd nos. are:",odd_count)
Output:
total even nos. are: 3
total odd nos. are: 2
2) Without "range" in for loop (with correct output):
n=[3,5,1,0,2]
even_count, odd_count = 0,0
for i in (n):
if (i%2==0):
even_count =1
else:
odd_count =1
print("total even nos. are:",even_count)
print("total odd nos. are:",odd_count)
Output:
total even nos. are: 2
total odd nos. are: 3
CodePudding user response:
If using range
, i is the index. You can test this by using:
>>> for i in range(5):
... print(i)
0
1
2
3
4
To check if the number is even, use if num[i] % 2 == 0:
Just as a sidenote, your code can be simplified further:
>>> even_count = len([x for x in n if not x % 2])
>>> odd_count = len([x for x in n if x % 2])
>>> even_count, odd_count
(2, 3)
CodePudding user response:
when you use for i in n you re iterating over the list so i gonna take the list values in this case i=3 then on the second loop i=5 ....