Python 如何检查for循环中的特定值,然后结束它?

Python 如何检查for循环中的特定值,然后结束它?,python,csv,Python,Csv,今天是我第一次学习csv和python。对不起,如果我问的问题已经回答了。我正在使用csv读卡器。假设我有一个包含以下行的文件: {'age': '20', 'name': 'Alice'} {'age': '21', 'name': 'Freddie'} {'age': '17', 'name': 'Bob'} 我将创建一个程序,允许用户输入他们的名字。如果它与数据匹配,它将输出true。我尝试在内部使用for循环和if-else语句 但是,它循环整个数据,而不是我正在查看的特定数据。例如,

今天是我第一次学习csv和python。对不起,如果我问的问题已经回答了。我正在使用csv读卡器。假设我有一个包含以下行的文件:

{'age': '20', 'name': 'Alice'}
{'age': '21', 'name': 'Freddie'}
{'age': '17', 'name': 'Bob'}
我将创建一个程序,允许用户输入他们的名字。如果它与数据匹配,它将输出true。我尝试在内部使用for循环和if-else语句

但是,它循环整个数据,而不是我正在查看的特定数据。例如,如果我输入Bob,我得到

Enter Name:Bob
No record found
No record found
true
而不是

Enter Name:Bob
true
我相信这是因为我创建了for循环,但我仍然不确定如何应对它

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")
Bob位于最后一行,因此它必须从头开始遍历所有行,直到找到Bob,然后它才存在

您可能只想打印最后没有找到的记录,而不是在每次迭代中。下面是一个使用标志来记住是否找到术语的建议:

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")
Bob位于最后一行,因此它必须从头开始遍历所有行,直到找到Bob,然后它才存在

您可能只想打印最后没有找到的记录,而不是在每次迭代中。下面是一个使用标志来记住是否找到术语的建议:

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")
将未找到记录的消息放入for循环是错误的

您在for循环中输入的任何内容都可以运行0、1或多次。对于“未找到记录”消息,许多消息没有意义

因此,该消息必须超出for循环:

将未找到记录的消息放入for循环是错误的

您在for循环中输入的任何内容都可以运行0、1或多次。对于“未找到记录”消息,许多消息没有意义

因此,该消息必须超出for循环:

Python中的for和while循环后面实际上可以有一个else。只有循环未被中断时,才会输入此子句。因此,您可以缩进else子句:

Python中的for和while循环后面实际上可以有一个else。只有循环未被中断时,才会输入此子句。因此,您可以缩进else子句:

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")