So I'm making this login system and I want new username to be added to the existing list and then save it there.
Code:
def login():
usernames = ["username1", "username2", "username3"]
passwords = ["pass1", "pass2", "pass3"]
print("Login")
username = input("Username: ")
if username not in usernames:
print("User doesn't exist")
input("Make an account? ")
if "yes":
print("Account Setup")
new_username = input("Username: ")
usernames.append(new_username)
print(usernames)
new_password = input("Password: ")
passwords.append(new_password)
print(passwords)
login()
else:
sys.exit()
else:
password = input("Password: ")
if password not in passwords:
print("Incorrect password")
login()
elif usernames[0] != passwords[0]:
print("Incorrect password")
login()
elif usernames[1] != passwords[1]:
print("Incorrect password")
login()
elif usernames[2] != passwords[2]:
print("Incorrect password")
login()
When I add new user their info is saved but when login() here is used and the login process starts again the input data is lost, the account i just created doesn't exist anymore.
if "yes":
print("Account Setup")
new_username = input("Username: ")
usernames.append(new_username)
print(usernames)
new_password = input("Password: ")
passwords.append(new_password)
print(passwords)
login()
Every time you call the login function you are setting password and username variable back to start. In this line:
usernames = ["username1", "username2", "username3"]
passwords = ["pass1", "pass2", "pass3"]
If you put those lines out of the function it will work.
BTW:
Don`t use two lists for passwords and usernames. It is inefficient and unnecessarily complicated. Use a dictionary. Like this:
logins = {"Jack": 1234, "Paul": 4321}
If you want two add new logins use:
logins["Oliver"] = 7531
If you want to check if username exists:
if "Jack" in logins:
print("Jack is a username")
Check if password is correct:
if logins[username] == inputed_password:
print("Password is correct.")
Note:
All of these names and passwords are made up. You can use any you want.
Related
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
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()
userlist = {"MMonroe": "SomeLikeItHot1962",
"NMandela": "Justice_27years",
"ALincoln": "Number_16"}
username = input("What is you username? (FLastname)")
if username in userlist:
passw = input("What is your password? :")
if passw in username:
passwnew = input("Enter password again:")
else:
newac = input("password is invalid, try again or would you like to create a new account(y/n)?")
if input == "y":
username = input("What is you username? (FLastname)")
passw = input("What is your password? :")
passwnew = input("Enter password again:")
else:
print("Try again later or create new account")
if passw != passwnew:
print("The password is invalid, try again")
else:
print("Welcome to the website")
Seems like you meant to check if the password for that user was incorrect. Don't use in for that
if passw != userlist[username]
Also, if input == "y" will never be true unless you overwrite the input() function with a string variable
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()
I'm coding myself a "simple" login system everything works ok up until the LOGIN part.
The while loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where the while loop would happen over and over again.
import re
users = {}
status = ""
while status != "r":
status = input("Press R to register!\n")
if status == "r":
createUser = input("Create your Username: ")
while len(createUser)< 5: #checks user len
print("Username should contain at least 5 characters!")
createUser = input("Create your Username: ") #repeat if user len < 5
while not re.match("^[a-z]*$" , createUser): # denies blank spaces
print("Cannot use blank spaces")
createUser = input("Create your Username: ")
if createUser in users:
print("Username already used!")
else:
createPass = input("Create your Password: ")
while len(createPass) < 5: #checks pass len
print("Password too short!\n Password should contain at least 5 characters!\n")
createPass = input("Create your Password: ") #repeat if pass len < 5
while not re.match("^[a-z]*$", createPass): # denies blank spaces
print("Cannot use blank spaces")
createPass = input("Create your Password: ")
else:
users[createUser] = createPass #adds user and pass to users
print("User created!")
#LOGIN
for createUser in users:
username = input("Username: ")
if username == createUser in users:
password = input("Password: ")
else:
while username != createUser:
print("User unregistered! Please register!")
createUser = input("Create your Username:")
First, "^[a-z]*$" tests for no lowercase letters, it does not mean "no blank spaces", so I have corrected that for you with "\\s+"
You really need to learn about methods and break your problem down.
1) Ask for the username
def get_username():
while True:
uname = input("Create your Username: ")
if len(uname) < 5:
print("Username should contain at least 5 characters!")
continue
if re.search("\\s+", uname):
print("Cannot use blank spaces")
continue
break # input successful
return uname
2) Ask for the password
def get_password():
while True:
passwd = input("Create your Password: ")
if len(passwd) < 5:
print("Password too short!\n\tPassword should contain at least 5 characters!\n")
continue
if re.search("\\s+", passwd):
print("Cannot use blank spaces")
continue
break # input successful
return passwd
3) Register
def register():
while True:
uname = get_username()
if uname not in users:
break # continue to get password
else:
print("Username already used!")
passwd = get_password()
if passwd:
users[uname] = passwd
print("User created!")
4) Attempt login (3 max attempts). It is currently unclear how you want to run this...
def login():
for i in range(3):
username = input("Username: ")
if username in users:
password = input("Password: ")
if users[username] != password:
print("Wrong username or password")
else:
print("User does not exist")
else:
print("Max attempts reached")
5) (optional) Learn about D.R.Y since your tests are essentially the same
def test_input(s):
if len(s) < 5:
print("Input should contain at least 5 characters!")
return False
if re.search("\\s+", s):
print("Cannot use blank spaces")
return False
return True
6) Run some code that uses all these methods.
status = input("Press R to register!\n")
if status.lower() == "r":
register()
Try this:
def login():
username = input("Username: ")
if username not in users:
print("User unregistered! Please register!")
register()
return
password = input("Password: ")
if users[username] != password
print("Password invalid")
I've rewritten your code here. Notice how I've broken it down into functions which do one thing:
usernameValidator
passwordValidator
getUsername
getPassword
register
login
Beginning of the program:
import re
users = {}
Now we define some validators to check if the username/password are correct:
def usernameValidator(username):
errorMessage = ""
if len(username) < 5:
errorMessage += "Username should contain at least 5 characters!\n"
if not re.match("^[a-z]*$" , username): # Note... this checks for more than just blank spaces!
errorMessage += "Cannot use blank spaces\n"
if username in users:
errorMessage += "Username already used!\n"
return errorMessage
def passwordValidator(password):
errorMessage = ""
if len(password) < 5:
errorMessage += "Password should contain at least 5 characters!\n"
if not re.match("^[a-z]*$" , password): # Note... this checks for more than just blank spaces!
errorMessage += "Cannot use blank spaces\n"
return errorMessage
Now we write the getUsername/getPassword functions which talk with the user:
def getUsername():
username = input("Create your Username: ")
errorMsg = usernameValidator(username)
print(errorMsg)
return username if errorMsg == "" else ""
def getPassword():
password = input("Create your Password: ")
errorMsg = passwordValidator(password)
print(errorMsg)
return password if errorMsg == "" else ""
Putting it all together, we write register/login:
def register():
username = ""
password = ""
while username == "":
username = getUsername()
while password == "":
password = getPassword()
users[username] = password
print("User created!")
def login():
username = input("Username: ")
if username not in users:
print("User unregistered! Please register!")
register()
return
password = input("Password: ")
if users[username] != password:
print("Password invalid")
Finally, we may run:
while True:
status = input("Press R to register!\nPress L to login\n")
if status.lower() == "r":
register()
if status.lower() == "l":
login()
Try it online.