Mark Schacter
Mark Schacter

Reputation: 17

can't get a simple counter function to work

I have looked at this piece of code over and over again and can't figure out what I am doing wrong!

word='banana'
def counting(x):
    count=0
    for i in word:
        if i=='a':
            count=count+1
            return count
print (counting(word))

The result should be 3 (3 instances of 'a' in 'banana'). But the actual output is 1. How should I fix my code?

Upvotes: 0

Views: 173

Answers (2)

Philip Wrage
Philip Wrage

Reputation: 1569

Your return statement appears to be indented so as to be within the if statement within the loop. Make sure you are not returning the count until the loop fully completes.

word='banana'
def counting(x):
    count=0
    for i in x:
        if i=='a':
            count=count+1
    return count
print (counting(word))

Upvotes: 2

Epion
Epion

Reputation: 518

This is because you return count inside of your for loop. The first time 'a' is found in your word, you will immediately return from the function.

Hence why your function will always either return 0 if no char was found, or 1 if any char was found.

By the way - this logic is already built-in as a string method in python.

count = word.count('a')

will do the trick.

Upvotes: 0

Related Questions