Python || Count The Total Number Of Characters, Vowels, & UPPERCASE Letters Contained In A Sentence Using A ‘For Loop’
Here is a simple program, which demonstrates more practice using the input/output mechanisms which are available in Python.
This program will prompt the user to enter a sentence, and then display the total number of uppercase letters, vowels and characters contained within that sentence. This program is very similar to an earlier project, this time, utilizing a for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
def main(): # declare variables numUpperCase = 0 numVowel = 0 numChars = 0 sentence = "" # get data from user sentence = input("Enter a sentence: ") # use a for loop, iterating over each item in the sentence for character in sentence: # do nothing, we dont care about whitespace if(character == ' '): continue # check to see if entered data is UPPERCASE if((character >= 'A') and (character <= 'Z')): numUpperCase += 1 # increment total number of uppercase by one # check to see if entered data is a vowel if((character == 'a')or(character == 'A')or(character == 'e')or (character == 'E')or(character == 'i')or(character == 'I')or (character == 'o')or(character == 'O')or(character == 'u')or (character == 'U')or(character == 'y')or(character == 'Y')): numVowel += 1 # increment Total number of vowels by one numChars += 1 # increment total number of chars being read # display data print("nTotal number of UPPERCASE letters: t%d" %(numUpperCase)) print("Total number of vowels: tt%d" %(numVowel)) print("Total number of characters: tt%d" %(numChars)) if __name__ == "__main__": main() # http://programmingnotes.org/ |
QUICK NOTES:
The highlighted portions are areas of interest.
Notice line 12 contains the for loop declaration. Note that each statement within the for loop block must be uniformly indented, otherwise the code will fail to compile.
Once compiling the above code, you should receive this as your output
Enter a sentence: My Programming Notes Is Awesome.
Total number of UPPERCASE letters: 5
Total number of vowels: 11
Total number of characters: 28
Leave a Reply