I need to check if every string in a list is in titlecase. If yes return True - if not return 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
thanks a lot!
CodePudding user response:
You're returning immediately in both the if
and else
blocks. That ends the loop in both cases.
You should only return in the if
block. 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.
def all_title_case(word_list):
return all(word.istitle() for word in word_list)
CodePudding user response:
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
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?
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))