'How to print a message if input does not match data in CSV?

This is my code that runs:

import csv

#input name you want to search
name = input('Enter name to find\n')

#read csv, and split on "," the line
csv_file = csv.reader(open('test.csv', "r"), delimiter=",")

#loop through the csv list
for row in csv_file:
        #if current rows 1st value is equal to input, print 2nd value
    if (name == row[0]):
        print (row[1])
        #if current rows 2nd value is equal to input, print 1st value
    if (name == row[1]):
        print (row[0])

I can't add

else:
    print("invalid input")

after the two if because it will print tons of it as it loops thru the whole CSV file.

Also, I have tried to add the following codes outside of the for, but the invalid message will still print even the input matches the CVS file

if (name not in csv_file):
    print("invalid input")


Solution 1:[1]

Break out of the loop if you find a match. Then use else: on the for statement to execute code if the loop finishes without breaking.

for row in csv_file:
        #if current rows 1st value is equal to input, print 2nd value
    if (name == row[0]):
        print (row[1])
        break
        #if current rows 2nd value is equal to input, print 1st value
    if (name == row[1]):
        print (row[0])
        break
else:
    print("Invalid input")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1