List Index Error out of range - python

When I run my code I get this message:"in Login if username == login_info[0] and password == login_info[1]: IndexError: list index out of range"My code used to work before but I don't understand why it doesn't work anymore.
#Registration
def Register():
username = input("Please input the first 3 or 4 letters of your first name and your year: ")#Gets the user to create a username
validate()#Calls upon the password validate()
file = open("AccountFile.txt","a") #Opens the text file called "AccountFile"
file.write(username)#Writes the users username into the text file.
file.write(" ")
file.write(password)#Writes the users password into the text file.
file.write("\n")
file.close()#Closes the text file "AccountFile"
#Login
def Login():
username = input("Please enter your username: ") #Asks the user to enter their username that they created
username = username.strip() #Any spaces that the user may put in will not affect the code and be removed
password = input("Please enter your password: ") #Ask the user to enter their password that they created
password = password.strip()
for line in open("AccountFile.txt","r").readlines(): #Reads the lines in the text file "AccountFile"
login_info = line.split() #Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("You have succesfuly logged in!") #Lets the user know that they have succesfully logged in
return True
print("Incorrect credentials.")
return False
#Validation
def validate():
while True:
global password #Makes the password global meaning the function global can be called upon anywhere in the code
password = input("Enter a password: ") #Asks the user to create a password
password = password.strip()
if len(password) < 8: #Checks whether the password is at least 8 letters long
print("Make sure your password is at least 8 letters")
elif re.search('[0-9]',password) is None: #Makes sure that the password has a number in it
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None: #Makes sure the password has a capital letter in it
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
#DisplayMenu
def DisplayMenu():
status = input("Are you a registered user? y/n? ") #Asks the user if they already have a registered account
status = status.strip()
if status == "y":
Login()
elif status == "n":
Register()
DisplayMenu()

Related

How do i make a login signup system in python?

im trying to write code in python that basically its so that in the terminal you input whether you want to signup or log in if you already signed up
i cant really figure out how to make it so that the signup input gets stored in a dictionary and then later when you try to enter the username and password it makes sure its the same one from the signup feature
thanks in advance
so far ive tried
accounts = {"user":"password", "user2":"password2"}
login_or_signup = input("Login or signup? ")
if login_or_signup.upper() == 'LOGIN':
username = input("Enter your username: ")
if username in list(accounts.keys()):
password = input("Enter your password: ")
if password in list(accounts.values()):
print("Logged in successfully.")
else:
print("Account credentials do not match.")
else:
print("Account not found.")
elif login_or_signup.upper() == "SIGNUP":
username = input("Enter your username: ")
password = input("Enter your password: ")
accounts.update({user,password})
but im getting an error
You have a typo in your last line, it should be username instead of user. Also : instead of ,
accounts.update({username: password})
That will make your program not fail in both options.
However, first, you are not checking properly the password, you need to grab the user and check if the password corresponds to the user in your dictionary.
Additionally, your program will finish right after you set up your new signup. You can add a while True loop at the top and break accordingly in the condition you would like to do so (example)
You should check if input password, matches the input username.
accounts = {"user": "password", "user2": "password2"}
login_or_signup = input("Login or signup? ")
while True:
if login_or_signup.upper() == 'LOGIN':
username = input("Enter your username: ")
if username in accounts:
password = input("Enter your password: ")
if accounts[username] == password:
print("Logged in successfully.")
else:
print("Account credentials do not match.")
else:
print("Account not found.")
elif login_or_signup.upper() == "SIGNUP":
username = input("Enter your username: ")
password = input("Enter your password: ")
accounts[username] = password

Username search in file python

I am trying to find a username from a txt file. (I know it is not security wise, but it is for testing purposes) Below is my code I am using and where I find the username from any line in file, save it to a list and then verify the password from that list. But it only finds the first line in file. All the other usernames after line 1 gets "Username not found"
with open("user.txt","r") as file:
for line in file.readlines():
login_info = line.rstrip("\n").split(", ")
while True:
username = input("Please enter your username: ")
if username == login_info[0]:
print("Username found!\n")
while True:
password = input("Please enter your password: ")
if password == login_info[1]:
print("Password correct!\n")
print(f"Welcome {username}!\n")
return options()
else:
print("Password incorrect.")
else:
print("Username not found.")
The txt file looks like this:
admin, adm1n
pete, p3t3
mark, m#rk
Where each line has the username as first string followed by comma and then the password.
If anyone could help me or point me in the right direction for answers.
There are multiple issues with your code like you are opening the file 2 times, which is unneccessary, secondly you need to check the user provided username against all the username not only login_info[0]
You can try something like
username_password_map = {}
with open('user.txt') as f:
for line in f.readlines():
username, password = line.rstrip('\n').split(', ')
username_password_map[username] = password
username = input("Please enter your username: ")
if username in username_password_map:
while True:
password = input("Please enter your password: ")
if password == username_password_map[username]:
print("Password correct!\n")
print(f"Welcome {username}!\n")
break
else:
print("Password incorrect.")
else:
print("Username not found.")

Unable to compare input variable to data within a .txt / Unable to read file to compare data

Currently I'm in the process of making a program where you can both login and register and the username/password are stored in a separate .txt file.
Registering is working fine, the username and password is written without issue but I am having issues with reading from the file in both userRegister and userLogin
The .txt file is formatted by username,password and I was wondering how I would go about reading from the file with the intention of comparing loginUsername and loginPassword to username_password and comparing registerUsername to existing usernames to ensure there are no duplicates.
username_password = open("savedCredentials.txt", "r+")
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
registerPassword()
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
username_password.close()
A few things:
You aren't calling any functions in your above code, so nothing will run as it stands.
You cannot iterate a Text wrapper, you can get around this by just reading your file by .read()
If you close() the file outside of your functions, you'll get an error that the file is closed, close the file within your function instead (whenever the user is done).
It appears once you go through the conditional if search, the .read() doesn't work anymore for the 2nd round. Don't quite know why (maybe someone else here can go into more detail), but the workaround is instead convert your file to a list, and search through that instead.
The below works, but it is a bit ugly (I have to go know, but wanted to post this real quick so you have at least a working example, and can build off of it).
username_password2=[]
with open("savedCredentials.txt", "r+") as file:
for lines in file:
a=lines.replace(',',' ')
b=a.split()
username_password2.append(b)
username_password = [x for y in username_password2 for x in y]
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
while True:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
register.close()
break
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print(username_password)
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
startMenu()
You have to add the read function to your file opening.
replace the line username_password = open("savedCredentials.txt", "r+")
by
username_password = open("savedCredentials.txt", "r+").read()
then you have to remove the line username_password.close()
also, you need to call your startMenu function so add startMenu() at the bottom of your code.

Is there any reason why this code wouldnt work at the start of of some Python code?

This code is at the start and when I run the code it doesn't do anything and nothing shows up, please help?
users = {}
status = ""
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
I expect the output to be a login system that then leads to a quiz but when I run it all I get is blank space
All you're doing is creating a couple of variables and declaring some functions.
Neither of those things will result in any output. If you want the functions to run, you'll actually need to call them from somewhere, such as by putting register() or login() (with no indentation) after the function definitions.
You defined the functions, but didn't call either, you should call one or both at the end of your script like :
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
login()

How to check text file for usernames and passwords

I'm writing a program which will need a user to register and login with an account. I get the program to have the user make their username and password which are saved in an external text file (accountfile.txt), but when it comes to the login I have no idea how to get the program to check if what the user inputs is present in the text file.
This is what my bit of code looks like :
def main():
register()
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.close()
login()
def login():
check = open("accountfile.txt","r")
username = input("Please enter your username")
password = input("Please enter your password")
I have no idea what to do from this point.
Also, this is what a registered account would look like in the text file:
Ha2001 examplepassword
After opening the file, you can use readlines() to read the text into a list of username/password pairs. Since you separated username and password with a space, each pair is string that looks like 'Na19XX myPassword', which you can split into a list of two strings with split(). From there, check whether the username and password match the user input. If you want multiple users as your TXT file grows, you need to add a newline after each username/password pair.
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines(): # Read the lines
login_info = line.split() # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False

Categories