Python Forum
Count Letters in a Sentence (without using the Count Function) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Count Letters in a Sentence (without using the Count Function) (/thread-11011.html)



Count Letters in a Sentence (without using the Count Function) - bhill - Jun-18-2018

Hello all,

Newbie Pythoner here.

I have been tasked with Counting Letters in a Sentence. However, I cannot use the Count function. What I have to do is the following:

1) Write a program that asks the user to input a sentence.

2) The program will ask the user what two letters are to be counted.

3) You must use a “for” loop to go through the sentence & count how many times the chosen letter appears in the sentence.

My code is below. As you can see, I used the count function to obtain an understanding of how the function works. My code is still non-functioning.

Anyways, can anyone provide a little guidance of how I can find how to letters can be counted using a For loop and not using the counting function?


sentence = "Hello World"

lettersToFind = 'L', 'E'
count = 0
for INDEX in range (0, len(sentence), 1):
    if sentence[INDEX] == lettersToFind:
       count = count + 1
       print("The", lettersToFind,"were found at index:", INDEX)
print(lettersToFind, "was found", count, "times")



RE: Count Letters in a Sentence (without using the Count Function) - Larz60+ - Jun-18-2018

to get each letter, use:
for letter in sentence:
    ...
remember that a string is a list or characters, so above will get a letter for each iteration.


RE: Count Letters in a Sentence (without using the Count Function) - cryomick - Jun-18-2018

The code you have written has almost all the correct elements, but it doesn't work for a few reasons:

1. 'lettersToFind' is a tuple and not a single letter. Ever. So your comparison condition always fails. But Python does provide a dead easy way of fixing this. Since 'lettersToFind' is a tuple, every time you need to check if the letter under consideration is 'in' this data container.
So change line 6 to
if sentence[INDEX] in lettersToFind:
2. The characters in 'Hello World' are of different font cases. For example, if you were to run your code, it would say that 'L' is not found in sentence. That is because it isn't in your sentence. The lowercase version of it is.
So change line 6 to
if sentence[INDEX].upper() in lettersToFind:
3. With 1 and 2, your code will run fine. It's just that the places you are printing out 'lettersToFind' cause me pain. Inside the loop, if found, just print out sentence[INDEX] and its position.

I hope this helped.


RE: Count Letters in a Sentence (without using the Count Function) - bhill - Jun-19-2018

Thank you all! Because of your help, I was able to code an algorithm that worked perfectly!