fdfdfd
fdfdfd

Reputation: 501

How to check a specific value in a for loop and then end it?

Today is my first time learning csv and python. Sorry if i am asking a question that has been answered. I am using csv dictreader. lets say i have a file with these rows:

{'age': '20', 'name': 'Alice'}
{'age': '21', 'name': 'Freddie'}
{'age': '17', 'name': 'Bob'}

I will be creating a program that allow user to input their name. Should it match the data, it will output true. I tried using for loop and an if else statement inside.

However, it loops the entire data instead of the specific data i am looking at. For example, if i input "Bob", i get

Enter Name:Bob
No record found
No record found
true

instead of

Enter Name:Bob
true

I believe this is because of the for loop I've created but I'm still not sure how to counter it.

import  csv

name1 = input("Enter Name:")

filePath = "data.csv"
with open(filePath) as  csvfile:
    reader = csv.DictReader(csvfile)    
    for row in reader:
        if name1 == row['name']:
            print("true")       
            break            
        else:                     
            print("No record found")

Upvotes: 1

Views: 730

Answers (3)

Graipher
Graipher

Reputation: 7186

for (and while) loops in Python actually can have an else after them. This clause will only be entered if the loop was not interrupted by a break. So you can just de-indent your else clause:

with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)    
    for row in reader:
        if name1 == row['name']:
            print("true")       
            break
    else:                     
        print("No record found")

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

It is wrong to put the No record found message into the for loop.

Whatever you put into the for loop can be run 0, 1 or many times. For the No record found message, the many doesn't make sense.

Therefore that message has to go outside the for loop:

for row in reader:
    if row['name'] == name1:
        print("found it")
        return
print("no record found")

Upvotes: 1

Ralf
Ralf

Reputation: 16505

Bob is in the last row, so it has to iterate over all the rows from the start till it finds Bob and then it exists.

You probably want to just print No records found at the end, not in every iteration. Here is a suggestion using a flag to remember if the term was found or not:

import  csv

name1 = input("Enter Name:")
was_found = False

filePath = "data.csv"
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)    
    for row in reader:
        if name1 == row['name']:
            print("true")
            was_found = True
            break            

if not was_found:
    # looked at every row and did not find search term
    print("No record found")

Upvotes: 2

Related Questions