Bayzid Ahmed
Bayzid Ahmed

Reputation: 1

Exit nested for loop in python

I wanted to search through a csv file that will look up keywords from a list within the first two columns. I've managed to get it to work when a key word is found, but wanted to have a message if no keywords found. Unfortunately the message "not found" comes out four times. I just wanted this to come out once. Please can you help? What it's doing is going around each key word again.

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")
for row in csv.reader(f):
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            break
        else:
            print ("not found")
            break
f.close

Upvotes: 0

Views: 108

Answers (3)

Dleep
Dleep

Reputation: 1065

import csv
keywords=["none","blank","off","screen","blank"]

f=open("CSVSolutions.csv")
for row in csv.reader(f):
    if row[0] in keywords or row[1] in keywords:
        print(row[2])
    else:
        print ("not found")
f.close

I figured avoiding nested for entirely was easier. It may seem slower to iterate over the keywords list twice but it's basically equivalent to making two comparisons per item anyways.

Upvotes: 0

Jonathan
Jonathan

Reputation: 5864

Looks like you want to emit the message "Not found" only when the keywords were not found in the entire file?

try this:

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")

for row in csv.reader(f):
    found = False;
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            found = True
            break
    if not found:
        print ("not found")
        break

f.close()

The main point being that you should use another variable to track the state that you're looking for.

Upvotes: 3

junnytony
junnytony

Reputation: 3515

You can use for.. else here like so:

for keyword in keywords:
    if keyword == row[0] or keyword == row[1]:
        break
else:
    print("not found")

Upvotes: 3

Related Questions