简体   繁体   English

第一次迭代后循环停止

[英]Loop stops after first iteration

I need to check if every string in a list is in titlecase.我需要检查列表中的每个字符串是否都在 titlecase 中。 If yes return True - if not return False.如果是,则返回 True - 如果不是,则返回 False。 I have written the following:我写了以下内容:

word_list=["ABC", "abc", "Abc"]

def all_title_case(word_list): 
   for word in word_list: 
        if not word.istitle():
            return False
        else: 
            return True 

print(all_title_case(word_list))

My problem is that it seems that the loops stops after the first string (which i guess is because of return?)我的问题是循环似乎在第一个字符串之后停止(我猜这是因为返回?)

How could i make it go over the whole list?我怎么能让它遍历整个列表?

*I am new to python *我是python的新手

thanks a lot!多谢!

You're returning immediately in both the if and else blocks.您将立即在ifelse块中返回。 That ends the loop in both cases.这在两种情况下都结束了循环。

You should only return in the if block.您应该只在if块中返回。 If you make it through the entire loop without returning, you know that all the words are title case.如果您通过整个循环而不返回,您就会知道所有单词都是标题大小写。

def all_title_case(word_list): 
    for word in word_list: 
        if not word.istitle():
            return False
    return True 

You can also use the all() function instead of a loop.您还可以使用all()函数而不是循环。

def all_title_case(word_list): 
    return all(word.istitle() for word in word_list)

Return statement ends the execution of your function, if you return True only when your for iteration is done you will have what you want Return 语句结束您的函数的执行,如果您仅在 for 迭代完成时返回 True,您将拥有您想要的

In other words your return statement ends your for loop, you can read some about it on this question: How to use a return statement in a for loop?换句话说,你的 return 语句结束了你的 for 循环,你可以在这个问题上阅读一些关于它的内容: How to use a return statement in a for loop?

word_list=["ABC", "abc", "Abc"]

def all_title_case(word_list): 
   for word in word_list: 
        if not word.istitle():
            return False

   return True 

print(all_title_case(word_list))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM