First post here although I have lurked for many years
I am currently working on a programming project and am stuck. The goal of the project is to take input from a user, a username and password, and verify through a text file to see if it is correct. If correct, it will print "Welcome!" and end, if not, it will ask for the username and password and loop through until a correct combination is entered.
The textfile is in the following format:
Darth:Vader
Boba:Fett
R2:D2
ObiWan:Kenobi
Luke:Skywalker
Here is my code:
# Lets user know what this program will do
print("Please login");
# Opens accounts txt file
accounts_file = open("accounts.txt", "r")
# Flag to terminate while loop
complete = False
# Runs loop until username and password are correct
while complete == False:
# Asks user for username and stores as variable
usernameInput = input("Username:");
# Asks user for password and stores as variable
passwordInput = input("Password:");
# Reads each line of the text file line by line
# Darth:Vader
# Luke:Skywalker
# R2:D2
# ObiWan:Kenobi
# Boba:Fett
for line in accounts_file:
# Stores each line in file as a username/password combo
username, password = line.replace("\n","").split(":")
# If username and password match, breaks out of the loop and sets complete to True
if usernameInput == username and passwordInput == password:
complete = True
break
# Sets complete to False and loops back
else:
complete = False
continue
if complete == True:
print("Welcome!");
I can get it to run correctly if enter a correct name the first time: For instance:
Please login:
Username:Darth
Password:Vader
Welcome!
- ends program
If I enter the wrong name, it loops back like so:
Please login:
Username:Darth
Password:Fett
Username:.....
However, if I enter a wrong username and then correct username, it will not end the program like I want it to, and continue to loop: Example:
Please login:
Username:Luke Password:Vader
Username:Darth Password:Vader
Username:R2 Password:D2
Any idea what is causing it to not accept the next input by the user and finishing the loop?
Thank you for the help!
.readlines().Sets complete to False and loops backsection is unnecessary. You don't need to setcompleteto False, because it's already False. If it was True you would have already ended the for loop and the while loop. And you don't need thecontinuebecause you will automatically continue after you've reached the end of the for loop.