Why the count always equal to the word length here even if the condition is wrong?

Viewed 40
word = input('Enter a word\n')
letter = input('Enter a letter\n')
count = 0
for letter in word:
    if letter == word[count] :
        count = count + 1
print(count)

I am trying to count how many times the letter appear in the word. But somehow the count value always equal to the length of the word?

eg. word = try letter = y

the count should be 1 right? but the result is showing 3? I don't understand where the problem is..

Thanks in advance!

4 Answers

There's a built-in function that will help you but if you want your own loop then:

word = input('Enter a word\n')
letter = input('Enter a letter\n')
count = 0
for c in word:
  if c == letter:
    count += 1
print(count)

Better would be:

print(word.count(letter))

....and if you just want to be weird then...

print(sum(c == letter for c in word))

You can use collections module for this too:

import collections
word = input('Enter a word\n')
letter = input('Enter a letter\n')
occurences = collections.Counter(word)
print(occurences[letter])

Result:

Enter a word
try
Enter a letter
y
1

At the moment you go over each character in the word, and check if it is equal to the character at word[count]. Since you start at zero en increase by one this is always true:

word = try
letter = y
count = 0

# entering for loop:
for letter in word: (go over t, r, y) 
    if letter == word[count]: (word[0] = t, word[1] = r etc.)
        count += 1 (here you increase the index of word, hence the statement is always true.

What you want to do is to check if the character is equal to the letter:

word = input('Enter a word\n')
letter = input('Enter a letter\n')
count = 0
for character in word:
    if character == letter :
        count = count + 1
print(count)
word = input('Enter a word\n')
letter = input('Enter a letter\n')
count = 0
for element in word:
    if element == letter:
        count = count + 1
print(count)

Related