简体   繁体   中英

While loop in python login system keeps repeating and wont break

My teacher gave me an assignment to make a login system for just the username part and he's given the code but it doesn't work properly as the while loop keeps repeating for the user to input their username when they already have and doesn't move onto the next part of code. I don't think the code is even reading the file or splitting the lines either.

I've tried putting in the break function in different places and changing indents of the code but I'm so lost. I've also tried changing the variable "StudentDetails" to UserData (the name of the csv file) but it doesn't change anything.

#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.")

Actual result: Please enter your username: Aiza11 Please enter your username: Aiza11 Please enter your username: Aiza11 There seems to be a problem with your details.

Aiza11 is a username in the csv file but it keeps asking for me to input username three times before saying it's incorrect...

Your running into this problem because your not checking if its a valid username with your while loop. This should all be in a while loop. I would also open and close the file outside the loop so its not opening and closing the file every time. I would also add a section to catch too many attempts. Doing that you can remove the and statement in the while loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM