条件在for循环内时,while循环不会中断

时间:2019-04-04 15:57:34

标签: python csv

我有一个要求用户输入姓名的代码。如果名称在csv文件中,它将输出true,然后中断。如果数据没有输入,则循环将继续进行。但是,即使我的输出正确,它也会继续循环,如下所示:

Enter Name:Bob
true
Enter Name:

这是我的csv数据:

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

下面是我的代码:

    import  csv

filePath    =   "data.csv"
with    open(filePath)  as  csvfile:
    reader  =   csv.DictReader(csvfile)    
    was_found = False

    while True:
        nam1 = input("Enter Name:")

        for row in  reader:        

            if nam1 == row['name']:
                print("true")
                break
        if nam1 == "":
            print('Empty input, please enter again')

3 个答案:

答案 0 :(得分:3)

break的作用域是直接外部循环。这样会破坏for而不是while

答案 1 :(得分:1)

一个修复技巧,在结束循环时使用变量和检查变量。可能就是您的变量was_found的目的

import  csv

filePath    =   "data.csv"
with    open(filePath)  as  csvfile:
    reader  =   csv.DictReader(csvfile)    
    was_found = False
    have_to_break = False

    while True:
        nam1 = input("Enter Name:")

        for row in  reader:        

            if nam1 == row['id']:
                print("true")
                have_to_break = True
        if nam1 == "":
            print('Empty input, please enter again')

        if have_to_break:
            break

我很确定可以避免使用True,在阅读器中执行for行,然后获取input(“ name”)

答案 2 :(得分:0)

另一种方法是从函数返回值:

import  csv

def get_name(reader):
    while True:
        nam1 = input("Enter Name:")

        if nam1 == "":
                print('Empty input, please enter again')
                continue

        for row in reader:
                if nam1 == row['name']:
                        print("true")
                        return nam1

filePath = "data.csv"
with open(filePath) as csvfile:
        reader = csv.DictReader(csvfile)
        was_found = False
        nam1 = get_name(reader)