-2

我的老师给了我一个任务,让我只为用户名部分创建一个登录系统,他给出了代码,但它不能正常工作,因为 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 文件中的用户名,但它一直要求我输入用户名三次,然后才说它不正确...

4

1 回答 1

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
于 2019-06-16T22:08:17.363 回答