Brandon
Brandon

Reputation: 21

Write a program that determines how many vowels and consonants in a string python

Write a program with a function that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and returns the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.

Here is my code I have so far:

def main():
   mystr = input('Please enter a string: ')
   mystr.lower()
   index = 0
   vowelSet = set(['a','e','i','o','u'])
   vowels = 0
   consonants = 0

def runVowels(mystr):
    while index < len(mystr):
        if mystr[index] in vowels:
            vowels += 1
            index += 1
        print('This string consists of ' + mystr(vowels) + 'vowels')

def runConsonants(mystr):
    while index < len(mystr):
        if mystr[index] != vowels:
            consonants += 1
            index += 1
        print('This string consists of ' + mystr(consonants) + 'consonants')

main()

Where did I go wrong at and am i on the right track?

Upvotes: 0

Views: 7939

Answers (5)

Def test_case1(*arg):
arg=eval(input("enter the object:")

     vowels=0
       for x1 in arg:
           if(x1 in("AEIOUaeiou")):
               Vowels+=1
               Print("vowels:",x1)

      consent=0
      for y1 in arg:
          if(y1 not in("AEIOUaeiou")):
              Consents+=1
              print ("consent:",y1):

if(___name__=="__main__"):

      test_case1("arg")

Upvotes: 0

systemjack
systemjack

Reputation: 3005

Don't turn this example into your class ;-)

Checking it out might help you get yours working.

def charCounts(mystr):
   mystr = mystr.strip().lower()
   vowels = 0
   cons = 0
   for c in mystr:
        if c in 'aeiou':
            vowels += 1
        elif c >= 'a' and c <= 'z':
            cons += 1
   return vowels, cons

if __name__ == '__main__':
    mystr = input('Please enter a string: ')
    vowels, cons = charCounts(mystr)
    print('This string consists of {0} vowels and {1} consonants'.format(vowels, cons))

Upvotes: 0

doubleo
doubleo

Reputation: 4759

The code below was tested on python 2.7.3.

  1. You need to study about variable scoping, you cannot define a variable in one method and use it in another method.

  2. Study a bit about whats the best way to take input from user, sys is a really good library for that

Always, Always initialize your variables before you use them, Have provided comments inline.

def main():

   mystr = raw_input("Enter your String:")
   mystr.lower()
   #index = 0, index is useless here
   vowelSet = set(['a','e','i','o','u'])
   #vowels = 0, vowels is useless here
   #consonants = 0, consonants is useless here

   #Either pass vowelSet as argument or define them explicitly in the methods
   runVowels(mystr, vowelSet)
   runConsonants(mystr, vowelSet)

def runVowels(mystr, vowelSet):
    #index, vowels needs to be defined and assigned a default value here
    index = 0
    vowels = 0

    while index < len(mystr):
        if mystr[index] in vowelSet:
            vowels += 1

        # You need to increment index outside of the condition
        index += 1
 print 'This string consists of ', vowels , 'vowels'

def runConsonants(mystr, vowelSet):
    #index, consonants needs to be defined and assigned a default value here
    index = 0
    consonants = 0
    while index < len(mystr):
        if mystr[index] not in vowelSet:
            consonants += 1

        # You need to increment index outside of the condition
        index += 1
    print 'This string consists of ' , consonants , 'consonants'

main()

Sample Run:

$ python vow.py 
Enter your String:aeeiithy
This string consists of  5 vowels
This string consists of  3 consonants

Again, this program only prints number of vowels. If you need number of 'distinct' vowels, it would be a bit different. Hope this helps !

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55489

You're getting closer. You still have the mysterious mystr.lower() inside your loops. You should take it out of the loops, and you need to save the result it returns (the lower-case version of mystr) somewhere, eg mystr = mystr.lower(). I suggest you do that in main() and then pass the lower-case version to your counting functions.

Once you do that, runVowels() will be almost perfect. runConsonants() still needs a little more work. If a character isn't a vowel doesn't mean that it's necessarily a consonant - it could be a number, a punctuation mark, or a space.

It would be more Pythonic if the loops in your functions looped over the string itself, you don't need the index stuff. Check this out in the interpreter:

mystr = "This is a TEST string"
for letter in mystr:
    print(letter)

Also, the question specifies that each of your counting functions should return a number. So runVowels() and runConsonants() should return their counts to main() and let it take care of the printing.

Upvotes: 0

abarnert
abarnert

Reputation: 365875

You've got multiple problems here.

  • While you define functions named myVowels and myConsonants, you never call them. You probably want to do that at the end of your main function.

  • Inside main, mystr.lower() doesn't do anything useful. That function returns a new string, the all-lowercase equivalent to mystr, but you don't store that anywhere. Store it somewhere (whether back to mystr, or into a new variable) so you can use it.

  • Inside runVowels, the index += 1 comes inside the if statement. So, as soon as you find a consonant, you're going to pass over the if, miss incrementing index, and just loop over the same consonant over and over. Dedent that line. (You have this same bug again in runConsonants, and the same is true for all of the following bugs.)

  • Inside runVowels, the print call comes inside the while statement, so it's going to print the running total once for each letter, instead of just printing the total at the end. Again, dedent one line.

  • You create variables named index, vowels and vowelsSet in main, which means they're local to that function. You then access variables with those names in runVowels, where they don't exist. Each function has its own local namespace. Move those assignments from main to runVowels—or pass them into runVowels, the same way you do with mystr.

  • You create variables named vowels and vowelsSet, but then you try to access them as if they were both called vowels. Keep things straight, use the right names for the right values.

  • I'm not sure what mystr(vowels) is supposed to do. You can't call a string like a function. I think you wanted the builtin str function here. (However, you may want to look at string formatting, or just look at what happens when you pass multiple arguments to print; you rarely need to concatenate strings the way you're doing.)

I won't guarantee that fixing all of these problems will make your code do what you want—it's certainly necessary, but may not be sufficient.

However, hopefully understanding what's wrong with each of these should help you learn how to spot similar problems yourself (not how to avoid them—unless you're the greatest genius in history, you'll be writing bugs like this until the day you die, you'll just get better at testing, debugging, and fixing them).

Upvotes: 6

Related Questions