python登录系统中的while循环不断重复且不会中断

时间:2019-06-16 21:58:28

标签: python csv while-loop login-system

我的老师给我分配了一个仅用于用户名部分的登录系统的工作,并且给了他代码,但是它无法正常工作,因为while循环不断重复,要求用户在已有和不存在时都输入用户名不要继续进行代码的下一部分。我认为代码甚至都无法读取文件或拆分行。

我曾尝试将break函数放在不同的位置并更改代码的缩进,但是我很迷失。我还尝试过将变量“ StudentDetails”更改为UserData(csv文件的名称),但它没有任何改变。

#Login System
#First Name, Last Name, D.O.B, Email, Username, Password

UFound = False
UAttempts = 0 #Set to 0 tries to enter username
#Allow the yser to try login 3 times

while (UFound == False and UAttempts <3):
    UName = input("Please enter your username: ")
    UAttempts = UAttempts +1 #Has entered username once
    #Opens csv file and reads
myFile = open("UserData.csv","r")
for line in myFile:
    StudentDetails = line.split(",") #Splits line into csv parts
    if StudentDetails[4] == UName: #Username is in database
        UFound = True
myFile.close() #Close the data file

if UFound == True:
  print("Welcome to the quiz!")

else:
  print("There seems to be a problem with your details.")

实际结果: 请输入您的用户名:Aiza11 请输入您的用户名:Aiza11 请输入您的用户名:Aiza11 您的详细信息似乎有问题。

Aiza11是csv文件中的用户名,但它一直要求我输入三遍用户名,然后再说不正确...

1 个答案:

答案 0 :(得分:0)

您遇到了这个问题,因为您没有通过while循环检查其有效用户名。这应该全部在while循环中。我还将在循环外部打开和关闭文件,以免每次都不打开和关闭文件。我还将添加一个部分来捕获太多尝试。这样做可以在while循环中删除and语句。

myFile = open("UserData.csv","r")
while UFound == False:
    UName = input("Please enter your username: ")
    UAttempts = UAttempts +1 #Has entered username once
    if UAttempts >2:
       print('Too many attempts')
       break
    #Opens csv file and reads
    myFile = open("UserData.csv","r")
    for line in myFile:
       StudentDetails = line.split(",") #Splits line into csv parts
       if StudentDetails[4] == UName: #Username is in database
           print("Welcome to the quiz!")
           UFound = True


     else:
        print("There seems to be a problem with your details.")
myFile.close() #Close the data file