如何在函数的for循环中使用多个条件?

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

我还是 python 的新手,才刚刚开始学习。给定的任务是找出给定文本中标点符号、元音字母和常量的数量。但是每当我 运行 代码时,它只会给我一个 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

当程序到达 return 时退出循环。

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."))

输出:

count: 4, count2: 4, count3: 7

您正在检查标点符号后重新调整值,其余的将被忽略。所以你得到 0。你的代码对标点符号检查有效。

Return 应该在循环之外。

应该是:

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)

您正在使用 return 关键字,也就是说,下面的所有代码都不会 运行 并且该函数将 returns 变量 count.

请验证一下。