Returning true or false in a for loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Returning true or false in a for loop (/thread-14284.html) |
Returning true or false in a for loop - bbop1232012 - Nov-22-2018 Hey everyone, I'm trying to define a procedure that identifies if the length of each element in a list is the same length as the list. For example the list [[1,2],[3,4]] has a length of two and each element inside the list also has a length of two. The problem I'm running into is how to return True or False using a 'for loop' for certain test cases. For example in the below case, the list meets the criteria and returns true. def correct_length(n): for e in n: if len(e) != len(n): break return False return True print correct_length([[1,2,3], [2,3,1], [3,1,2]])But, when the criteria is not met as in the next example, the output is still true. def correct_length(n): for e in n: if len(e) != len(n): break return False return True print correct_length([[1,2,3], [2,3,1], [3,1,2,4]])I think the problem is probably something simple, but have been beating my head on the desk for a while trying to figure it out. Any help would be greatly appreciated. RE: Returning true or false in a for loop - ichabod801 - Nov-22-2018 The problem is that when the for loop ends, you return False, even though you should return True. The solution is to put the return False where the break is. The return will 'break' out of the function, serving the same purpose. Another useful trick for similar but more complicated situations is using else on a for loop: def check_len(sequence): for sub_list in sequence: if len(sub_list) != len(sequence): break else: return True return FalseThe else statement on the for loop triggers if the break statement was never used. RE: Returning true or false in a for loop - woooee - Nov-22-2018 Remove the break, and indent the return False to the same level as the break. RE: Returning true or false in a for loop - bbop1232012 - Nov-22-2018 Thanks a lot guys, I appreciate you clearing up my syntax confusion. Peace, Brian |