Chinmay Kamat Chinmay Kamat - 5 months ago 9
Python Question

Pythonic way to break out of loop

Total python beginner here.

I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.

I have to break out of looping, immediately after the match is found, to avoid needless looping.

Here is the code:

def DateZoneCity_downloaded_previously(Order_Date,ZoneCity): # function to check if a given DateZoneCity
# combination had already been completely downloaded
string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
with open(Record_File) as download_status:
DateZoneCity_exists = False
for line in download_status:
if string_to_match in line:
DateZoneCity_exists = True # if match found, then set "DateZoneCity_exists" to True
break # and break out from the [for line in download_status:] loop
if DateZoneCity_exists: return True
download_status.closed


I am searching for a more concise, pythonic way to structure the code. Is there anything I can do to make this better? Somehow to eliminate the need for "DateZoneCity_exists" and the second If statement?

Answer

This feels like a situation where any would be the best solution:

# Function to check if a given DateZoneCity
def DateZoneCity_downloaded_previously(Order_Date, ZoneCity):
    # Combination had already been completely downloaded
    string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0]
                                                      + "-" + ZoneCity[1]
    with open(Record_File) as download_status:
        return any((string_to_match in line) for line in download_status)

Note that in this case it will return False on negative rather than your current implementation that will return None, also note that it does break out of the looping immediately upon finding a positive result so it does not require looping through the entire file either way.

Comments