Gus Gus - 9 months ago 66
Python Question

Loop not functioning correctly

Working with data frames and this is the code I have for it.

numbers = 3
count=0
A = 0
B = 0
C = 0
for x in range(numbers):
if str(data.iloc[count])== 'A':
A += 1
elif str(data.iloc[count])== 'B':
B += 1
elif str(data.iloc[count])== 'C':
C += 1
count +=1
#this is to return the count to check if it works
print A
print B
print C


but for some reason when I run this code only the count for A increases.

i.e. if the data in the index had a 'A', 'B', 'B' its still returning A = 3 and B = 0 where it should be returning A = 1, B = 2, and C = 0

what am I doing wrong? thanks again.

Answer Source

Since your count += 1 is not within the for loop, count += 1 only runs once, after the for loop is complete. It needs to be indented. Alternatively, you do not need to use a count variable since x is already going through the range 0 to 3:

numbers = 3
A = 0
B = 0 
C = 0
for x in range(numbers):
    if str(data.iloc[x])== 'A':
        A += 1 
    elif str(data.iloc[x])== 'B':
        B += 1 
    elif str(data.iloc[x])== 'C':
        C += 1 

#this is to return the count to check if it works
print A
print B
print C