I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").
If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.
Any suggestions how to fix this?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
Edit
Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.
Any suggestions why?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()
Right now you are checking if the given password, passw, matches any keys in users (not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:
if passw == users[login]:
print "Login successful!\n"
EDIT:
For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use q to exit the program. It's because when you're inside displayMenu, you save user input in a local variable named status. This local variable does not refer to the same status where you are checking,
while status != "q":
In other words, you are using the variable status in two different scopes (changing the inner scope does not change the outer).
There are many ways to fix this, one of which would be changing,
while status != "q":
status = displayMenu()
And adding a return statement at the end of displayMenu like so,
return status
By doing this, you are saving the new value of status from local scope of displayMenu to global scope of your script so that the while loop can work properly.
Another way would be to add this line to the beginning of displayMenu,
global status
This tells Python that status within displayMenu refers to the global scoped status variable and not a new local scoped one.
change
if login in users and passw in users: # login matches password
to
if users[login] == passw: # login matches password
Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"
Please encrypt you passwords in database if you go put this online.
Good work.
import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178"
def checkPassword():
for key in range(3):
#get the key
p = raw_input("Enter the password >>")
#make an md5 object
mdpass = md5.new(p)
#hexdigest returns a string of the encrypted password
if mdpass.hexdigest() == password:
#password correct
return True
else:
print 'wrong password, try again'
print 'you have failed'
return False
def main():
if checkPassword():
print "Your in"
#continue to do stuff
else:
sys.exit()
if __name__ == '__main__':
main()
usrname = raw_input('username : ')
if usrname == 'username' :
print 'Now type password '
else :
print 'please try another user name .this user name is incorrect'
pasword = raw_input ('password : ')
if pasword == 'password' :
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print 'this service is temporarily unavailable'
else :
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
exit()
This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:
print("Steam Security Software ©")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
print ("Now type password")
else :
print ("please try another user name. This user name is incorrect")
password = input ("Password:")
if password == "password" :
print ("ACCESS GRANTED")
print ("<<Welcome Admin>>")
#continue for thins like opening webpages or hidden files for access
else :
print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
exit()
Related
Loging in with jack works fine but I cant login with jake even thought he exists in the array. It just skips the whole for loop "for i in storedusername". An help would be grateful.
Here's the code:
import pygame
import sys
import random
storedusername = ["jack","jack","jack","jake","jack","jack","jack",] # The place where the username is stored
storedpass = ["abcde","abcde","abcde","12345","abcde","abcde","abcde",] # The current place where the password is stored
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input("Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: # Loops through the items in the list
if i == user: # Compares the items in the list with the username that the user has entered
print("user found") # If the user was found then the program will tell the user that
pos = int(storedusername.index(user)) # Finds the position where the username is stored
print(pos)
for j in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
login()
You are using the variable i both for outer and inner loop, so it is changed inside.
It must be:
for i in ... :
...
for j in ... :
...
You were right to think that the indentation wasn't correct. As you had it before, if you entered a username not present in the list, you would still be asked for the password ten times for each user in storedusername (a total of 70 times!). Moving the block from for i in range(0,10) one indentation further fixes it.
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
# >>>> indent here
for i in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
# >>>>>
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
You may see that not working because of wrong indentation of that
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
block.
Please move it to to left, and it should be better.
That modified version
storedusername = ["jack", "jack", "jack", "jake", "jack", "jack",
"jack", ] # The place where the username is stored
storedpass = ["abcde", "abcde", "abcde", "12345", "abcde", "abcde",
"abcde", ] # The current place where the password is stored
(width, height) = (644, 412)
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input(
"Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
for i in range(0, 10): # Has 10 tries to do this loop
password = input(
"Enter Password: ") # The user enters the password which they think matches with the username.
# for i in range(0,10):
if password == storedpass[
pos]: # Goes to the position where the password matches the username is stored and compares the values.
print(
"password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
# --> wrong indentation
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
# <-- wrong indentation
else:
print(
"not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
# register()
login()
allows for
Enter Username: jack
jack
user found
0
Enter Password: abde
Pasword does not match try again
Enter Password: abcde
password match username
Process finished with exit code 0
I'm not going to modify the flow of your solution, but I'd suggest to write comments before the line, not in it. Also you should avoid variables shadowing (using the same variable like i in different scopes). The last thing is that you got slightly wrong indent for password checking - it was run even wihtout matched name. I allowed myself to propose version with all these modifiactions. Please take a look on that:
def login():
""" Function used to login"""
# Global the logins fucntion
global Login
Login = False
# User enters the username that they would like to login with
user = input("Enter Username: ")
print(user)
for stored_user_name in stored_user_names:
if stored_user_name == user:
print("user found")
pos = int(stored_user_names.index(user))
# Has 10 tries to do this loop
for try_attempt in range(0, 10):
# The user enters the password which they think matches with the username.
password = input("Enter Password: ")
# Goes to the position where the password matches the username is stored and compares the values.
if password == storedpasswords[pos]:
# Program returns if the username and password match
print("password match username")
Login = True # Turns login to True
return Login # Returnss Login
else:
# If the password does not match then the program will notify it.
print("Password does not match try again")
# If there are too many attempts than it will close.
print("too many attempts close the program")
else:
# If the username is not found than it will be promted that it is not found.
print("not found")
return Login
Hi i'm new in python and in programming in general ! i tried to make a login system with python but it doesnt seem to be working as i expect
the problem is even if i enter false login informations at the end the program will print login successful instead of printing incorrect username or password
NOTE : i'm not trying to make real login system it's just some practice form what i learned
signup_username = ""
signup_password = ""
login_username = ""
login_password = ""
false_login_info = False
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
signup()
print("Signup successful")
login()
if login_username != signup_username or login_password != signup_password :
print("Incorrect username or password")
else :
print("login successful")
EXPECTED Result :
1) if login informations are same as signup infos i should get :
- Login successful
2) if login informations are NOT same as signup infos i shoul get :
- Incorrect username or password
ACTUAL Result :
in both cases the program will print login successful
You need to return the values from your functions. The names defined inside the function are not the same as those that exist outside of the function. In this case, I have appended x to the names in the global scope to differentiate them from the ones inside the function to hopefully make it clearer. I could have used the same names both inside the function and outside; it wouldn't have made a difference. You can see more here.
There is no need to "initialise" the variables as empty strings before the function call. Instead, we'll just create them in the function, return them, and then unpack them into the variables ending in x.
false_login_info = False # You never use this
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
return signup_username, signup_password
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
return login_username, login_password
signup_usernamex, signup_passwordx = signup()
print("Signup successful")
login_usernamex, login_passwordx = login()
if login_usernamex != signup_usernamex or login_passwordx != signup_passwordx:
print("Incorrect username or password")
else :
print("login successful")
I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue
I am trying to make a working user registration program. When asked for the username, the system will look to see if the text entered has already been stored. If the username has already been stored, it will ask for the password for that user. However, if the username has not been stored, it will ask for a password. When these are entered, the script will then appendix onto a .txt of a .py file to make an new account. After the account has been made, the script can then read the .txt or .py file for the login information. My current login code:
loop = "true"
while(loop == "true"):
username = input("Enter Username: ")
password = input("Enter Password: ")
h = input ("Do You Need Help [Y/N]: ")
if(h == "Y" or h == "y" or h == "yes" or h == "Yes"):
print ("Enter username and password to login. If you do not have an account yet, enter 'Guest' as the username and press enter when it asks for the password.")
elif(h == "N" or h == "n" or h == "no" or h == "No"):
print (" >> ")
if(username == "Hello World" and password == "Hello World" or username == "Test User" and password == "Test User" or username == "Guest"):
print ("Logged in Successfully as " + username)
if(username == "Guest"):
print ("Account Status: Online | Guest User")
if not (username == "Guest"):
print ("Account Status: Online | Standard User")
How do you make a database that python can read from for the username and password? Also, how do you make it so that python can appendix to the database to add more usernames and passwords?
This is Python v3.3.0 Mac OSX 10.8
Thank you in advance!
Try using the pickle module:
>>> import pickle
>>> myusername = "Hello"
>>> mypassword = "World"
>>> login = [myusername, mypassword]
>>> pickle.dump(login, open("%s.p" % login[0], "wb")) #Saves credentials in Hello.p, because Hello is the username
>>> #Exit
Now to get it back
>>> import pickle
>>> try:
... password = pickle.load(open("Hello.p", "rb"))[1]
... username = pickle.load(open("Hello.p", "rb"))[0]
... except IndexError: #Sees if the password is not there
... print("There is no information for those credentials")
...
>>> password
'mypassword'
>>> username
'myusername'
If there is no password or username, it prints There is no information for those credentials... Hope this helps!
AND JUST A TIP: don't bother going through if(h == 'n'..., just do a h.lower().startswith("n") == True. .lower() makes everything lowercase, and str.startswith("n") checks if str starts with the letter n.
I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")
Seems like you just want
users[createUser] = createPassword