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!
>Solution :
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)