Search code examples
pythonmultiple-conditions

How to use multiple conditions in a for loop in a function?


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

Solution

  • 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)