Home > Enterprise >  How can I collect the vowels and consonants of a script without collecting empty spaces?
How can I collect the vowels and consonants of a script without collecting empty spaces?

Time:12-19

I was looking to see how I would be able to collect the consonants without counting any blank spaces in between words.

def main():
string=input("Enter a string here: ")
vowels=0
consonants=0

for i in string:
    if(i=='a'or i=='e'or i=='i'or i=='o'or i=='u' or i=='A' or i=='E'or i=='I' or i=='O' or i=='U'):
        vowels=vowels 1
    else:
        consonants=consonants 1


    
print('The string you have entered includes', vowels,'vowels and',consonants,'consonants!')

main()

CodePudding user response:

This code should collect vowels already. You can use elif(i=" ") to check for the spaces and use continue() to make loop skip them, and then else would be consonants (in case your user won't enter something like "][3||0!").

One way to make your life easier is to use .lower() method - this way you'd turn all the input to lowercase letters and you can cut your if (i="a"....) condition in half

CodePudding user response:

There are a number of ways to solve this.

The reason you are currently counting characters you do not want, is because you used else, but just because a character is not a vowel, does not mean it is a consonant.

You could use elif and check for all the consonants, but that would be a long and ugly condition.

Instead, you can use isalpha to make sure your current character is a letter first, then check if it is a vowel or a consonant.

vow = 'aeiou'

...

for i in string:
    if i.isalpha():
        if i.lower() in vow:
            vowels  = 1
        else:
            consonants  = 1

Note, that your current code does not comply with the requirements in your homework, but I will leave that part to you.

CodePudding user response:

Your code is pretty close. You are correctly counting the vowels. If you add to your else block a check to make sure you have a letter, then you are good to go.

else:
    if i in string.ascii_letters: #you may need to import string
        #now you know that i is a letter, but not a vowel
        consonants  = 1

Also, your vowels check can be simplified to

if i in 'aeiouAEIOU':

it does the same thing, but will probably be easier to read.

  • Related