循环CSV文件登录 - 循环3次,不确定原因

时间:2017-10-12 15:15:17

标签: python csv while-loop python-3.3

import csv

def login():
    global student
    student = []
    file = open("student.csv","r")       
    data = csv.reader(file)    

    UsernameVerified = False
    PasswordVerified = False

    while UsernameVerified == False:
        username = input("Username: ")
        for row in data:
            user = []
            student.append(row)
            print(UsernameVerified)

            for multi in row[5:6]:
                if username in multi:
                    print("found")
                    UsernameVerified = True
                    print(UsernameVerified)

这是我正在使用的当前代码。但是,当我运行此代码并输入正确的用户名时,它会发现用户3次不应该这样做。

当我输入错误的用户然后是正确的用户时,它根本找不到用户。

我正在为一个学校项目做这件事,并且有两位老师对此进行调查,到目前为止还没有取得任何进展。

Output when I input the correct User first

Output when I input the wrong User first, then the Correct one

新代码 ------

导入csv

def login():     全球学生     student = []

UsernameVerified = False
PasswordVerified = False

while UsernameVerified == False:
        file = open("student.csv","r")
        data = csv.reader(file)
        username = input("Username: ")
        for row in data:
            user = []
            student.append(row)
            print(UsernameVerified)

            for user in row[5:6]:
                if username in user:
                    print("found")
                    UsernameVerified = True
                    print(UsernameVerified)

while PasswordVerified == False:
        file = open("student.csv","r")
        data = csv.reader(file)
        password = input("Password: ")
        for row in data:
            user = []
            student.append(row)
            print(PasswordVerified)

            for pass1 in row[4:5]:
                if password in pass1:
                    print("found")
                    PasswordVerified = True
                    print(PasswordVerified)

1 个答案:

答案 0 :(得分:0)

对于第一个问题:它返回3次因为while循环只停止而for循环结束。如果你想要一个快速修复,当你登录用户时,在for循环中使用“break”。

对于发生的第二个问题,因为“data”变量指向文件末尾。基本上你打开文件,读到它直到你输入错误的用户结束,并保持在那里。尝试在“输入”之后使用“with”语句

打开文件