CountLetters
- Lim Long Teck
- Dec 30, 2021
- 1 min read
Write a Python program to
- Prompt user to input a sentence
- Count the occurrence of each letter in the input sentence
- Save the result to a dictionary letters where the key is the letter and the value is the occurrence of the key
- Display letters in alphabetical order of the key.
Program:
sentence = input('Enter a sentence: ')
newlist = []
for i in sentence:
i = i.lower()
if i not in newlist and i.isalpha():
newlist.append(i)
numlist = []
for ele in newlist:
count = 0
for alpha in sentence:
if ele == alpha.lower():
count += 1
numlist.append(count)
letters = {}
i = 0
while i <len(newlist):
letters[newlist[i]] = numlist[i]
i += 1
for n in letters:
print('{} : {}'.format(n, letters[n]))
Output:
Enter a sentence: hello
h : 1
e : 1
l : 2
o : 1
Comments