Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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..🙈

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading