Python Count function not increasing in tutorial video

Viewed 36

I am just learning python and am following a video course. I copied an example from the video, but the loop isn't working and being new I can't figure out why. The only change I've made is to add print statements to see what's happening. When I run it, both printing the count and the final print statement return 0, but it should be 4.

Can anyone shed some light on what's wrong with it?

def countChar(ch, teststring):
    count = 0
    print(ch)
    print(teststring)
    print(len(teststring))
    for i in range(len(teststring)):
        print(i)
        if teststring[i] == ch:
            count += 1
            print(count)
        return count

print(countChar('e', "the quick brown fox jumped over the lazy dog"))

Result

e
the quick brown fox jumped over the lazy dog
44
0
0
2 Answers

The return count statement is inside the for loop. You want to put it outside the for loop, but inside the function countChar. Simply do this to your code:

def countChar(ch, teststring):
    count = 0
    print(ch)
    print(teststring)
    print(len(teststring))
    for i in range(len(teststring)):
        print(i)
        if teststring[i] == ch:
            count += 1
            print(count)
    return count

print(countChar('e', "the quick brown fox jumped over the lazy dog"))

return count is inside for-loop, indent it to same level as for is.

Related