0

I'm still new to python and have just started learning. The task given is to find the amount of punctuation, vowels, and constants in a given text. But whenever I run the code it just gives me a 0.

def getInfo(text):

    pun = [".", ",", " ", "\'", "\"", "!"]
    vowels = ["a", "e", "i", "o", "u"]

    count = 0
    count2 = 0
    count3 = 0
    for char in text:
        if char in pun:
           count += 1
        return count
    
        if char.lower() in vowels:
           count2 += 1
        return count2
        
        if (not char.lower() in vowels) and (not char.lower() in pun):      
            count3 += 1
        return count3

4 Answers 4

1

You are retuning value after checking punctuation, rest of them are ignored. So you are getting 0. Your code is valid for punctuation check.

Sign up to request clarification or add additional context in comments.

Comments

1

When program reaches return it exits from loop.

def getInfo(text):

    pun = [".", ",", " ", "'", '"', "!"]
    vowels = ["a", "e", "i", "o", "u"]

    count = 0
    count2 = 0
    count3 = 0
    for char in text:
        if char in pun:
            count += 1

        if char.lower() in vowels:
            count2 += 1

        if (not char.lower() in vowels) and (not char.lower() in pun):
            count3 += 1
    return "count: {0}, count2: {1}, count3: {2}".format(count, count2, count3)

print(getInfo("We are in 2020."))

Output:

count: 4, count2: 4, count3: 7

Comments

0

Return should be outside the loop.

It should be :

def getInfo(text):

    pun = [".", ",", " ", "\'", "\"", "!"]
    vowels = ["a", "e", "i", "o", "u"]

    count = 0
    count2 = 0
    count3 = 0
    for char in list(text):
        if char in pun:
           count += 1
   
        if char.lower() in vowels:
           count2 += 1
        
        if (not char.lower() in vowels) and (not char.lower() in pun):      
            count3 += 1
    return (count, count2, count3)

getInfo('myname.is hello world!')

# (4, 6, 12)

Comments

0

You are using return keyword, that's, all the code below will not run and the function will returns the variable count.

Please, verify this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.