停止for python循环中的函数

停止for python循环中的函数,python,function,Python,Function,我在for循环中停止函数时遇到问题 def character(char_type,word,number): for i in range(len(word)): for e in range(len(char_type)): if word[i]==char_type[e]: if char_type==vowels: number[0]=number[0]+1

我在for循环中停止函数时遇到问题

def character(char_type,word,number):
    for i in range(len(word)):
        for e in range(len(char_type)):
            if word[i]==char_type[e]:
                if char_type==vowels:
                    number[0]=number[0]+1
                elif char_type==consonants:
                    number[1]=number[1]+1
                elif char_type==valid_symbols:
                    number=number
            else:
                number=[-1,-1]

如果number=[-1,-1],我需要函数终止,但我不知道如何终止。我试过在缩进的每一个层次上使用return,但仍然不起作用

我认为您应该使用break语句并检查它。

假设您的字符类型是一个有值的字典

字符类型={a':'元音','b':'辅音',…}

您可以像这样操作代码

   def character(char_type,word,number):

       for i in word:   #using range(len(word)) is a bad practice, you can directly access each character from a word

          if i in char_type.keys():

             if char_type[i] == vowels:
                number[0] = number[0]+1

             elif char_type[i] == consonants:
                number[1] = number[1]+1

             elif char_type[i] == valid_symbols:
                pass

         else:
            number=[-1,-1]
            break

同样,有几种方法可以为这一点编写逻辑。目前,这是我能想到的。希望这对你有用:)。

==!==。。。。。。(但是
return
会终止函数)
return
肯定会停止函数。但是
number==[-1,-1]
没有任何用处。作业是
=
,而不是
=
。为了更好的可读性,如果您不想在一个
elif
中执行任何操作,您应该考虑使用
pass
。或者完全删除冗余的
elif