In this exercise we will practice using loops to handle collections/containers. Your job is to write a program that asks the user to enter a sentence, then it counts and displays the occurrence of each letter.
Note: your program should count the letters without regard to case. For example, A and a are counted as the same.
Here is a sample run:
Enter a sentence: It's a very nice day today! a: 3 times c: 1 times d: 2 times e: 2 times i: 2 times n: 1 times o: 1 times r: 1 times s: 1 times t: 2 times v: 1 times y: 3 times
Notes:
How your program will be graded:
Language is python 3
# first we create a empty dictionary which will store key value pairs for different alphabets
Dict = {}
# ask for input from the user
sentence = input("Enter a sentence: ")
print() #print a blank line
# Fill the Dictionary so that it contains keys from 'a' to 'z' but values of all the keys are set to 0
# we iterate from 97 to 122 because 97 to 122 corresponds to ASCII value of 'a' to 'z'
for loop in range(97, 123):
key = chr(loop) # chr(loop+97) converts integer to character so that 97 converts to 'a', 98 converts to 'b' and so on
Dict[key] = 0 #set value of each key = 0
#then we iterate through each character in the input string
# if character is space or is not any alphabet then we skip or in other words we fill the dictionary only for alphabets from 'a' to 'z' or 'A' to 'Z' and not blank spaces and other characters
for character in sentence:
# if character is not a blank space and it lies between 'A' and 'Z' ot 'a' and 'z' then we enter the if condition
if character != ' ' and ((character >= 'A' and character <= 'Z') or (character >= 'a' and character <= 'z')):
# if character is uppercase alphabet then it needs to be converted into lower case by adding 32 to it
# we add 32 because ASCII value of 'A' is 65 and that of 'a' is 97 so we add 32
if character >= 'A' and character <= 'Z':
tempChar = ord(character) # convert character to integer using ord(character)
tempChar = tempChar + 32 # add 32 to integer
character = chr(tempChar) # convert integer to character
Dict[character] = Dict[character] + 1 #finally add the character to dictionary by incrementing its value
# then we iterate from 97 to 122 and again convert it back to character.
# if the value of this character is zero in the dictionary then we don't print it else we print character and its value
for loop in range(97, 123):
key = chr(loop)
if Dict[key] != 0:
print(key, " = ", Dict[key])
Get Answers For Free
Most questions answered within 1 hours.