而python登录系统中的循环会不断重复,并且不会停止

2024-09-30 19:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件csvtheto代码lineusernamemyfile
1条回答
网友
1楼 · 发布于 2024-09-30 19:33:08

你遇到这个问题是因为你没有在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

相关问题 更多 >