0
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!

Xavier
  • 25
  • 3
  • You overwrite `letter` in the `for` loop and you needlessly index `word`. Use `for c in word:` instead. –  Sep 09 '22 at 10:17

4 Answers4

1

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))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

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
Cow
  • 2,543
  • 4
  • 13
  • 25
0

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)
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
  • thank you for your help! it works for me but I don't understand the following if letter == word[count]: (word[0] = t, word[1] = r etc.) I don't understand why this statement is always true. the letter input is y, word[0] is t, why is it true??? – Xavier Sep 09 '22 at 10:33
  • Because if you go over a string in a for loop (`for letter in word`) each iteration the letter gets the value of the next character in word. Print for example what happens in your code: `for i in [1, 2, 3, 4]: print(i)` and `for letter in word: print(letter)` (note, you have to format those two lines yourself). – 3dSpatialUser Sep 09 '22 at 10:52
0
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)

raviteja k
  • 94
  • 1
  • 1
  • 6