Daquaris Georgino
Daquaris Georgino

Reputation: 7

Breaking a for loop in python?

I am trying to break a for loop that checks reads lines in another module. I notice that this function runs through every line of code in the module, but it only returns the boolean for the last line... how can I stop the loop as soon as it sees a false WITHOUT USING the break function? You don't have to worry about opening the file, I am capable of doing that

read_lines = file_handle.readlines()

for next_line in all_lines:

    check = next_line[0]

    if (check == ' '):
        result = False

    else:
        result = True
return result

Upvotes: 0

Views: 76

Answers (2)

cs95
cs95

Reputation: 403120

It's important to understand what exactly you want to return, and under what conditions, because this greatly affects what your function returns and when. For example, do you want to check if check == ' ' for even a single case? In which case, one return is enough.

for next_line in all_lines:
    if next_line[0] == ' ':
        return False

return True

Alternatively, you can use any:

return not any(x[0] == ' ' for x in all_lines)

Or, its counterpart, all, with an inverted condition:

return all(x[0] != ' ' for x in all_lines)

Note that str.isspace() is a more pythonic way of checking if a string is a whitespace character, although that makes a check for all whitespace characters (including tabs and newlines, not just whitespace characters).

Upvotes: 1

Sandeep Lade
Sandeep Lade

Reputation: 1943

You can add a return statement in your code , which will exit function as soon as it finds a match

read_lines = file_handle.readlines()

for next_line in all_lines:

    check = next_line[0]

    if (check == ' '):
        result = False
        #add a return here
        return result
    else:
        result = True

return result

Upvotes: 0

Related Questions