Reputation: 1
Newbie to python and just trying to get a grasp of things.
Ive written a practice piece of code where a user is asked to enter their username and password from this mock database. My question is how do I get the username to correlate with the password for any given user? So user "amy" password would be "apple". Do I need just a single variable setup as a dictionary instead or something along those lines?
list= ["amy", "chris", "jake"]
password = ["apple", "orange", "date"]
login = ("")
counter = 0
attempts = 5
out_of_attempts = False
while login not in list and not (out_of_attempts):
if counter < attempts:
login = input ("enter username: ")
counter += 1
else:
out_of_attempts = True
if out_of_attempts:
print ("Sorry login limit exceeded please try again later")
else:
pass
while login not in password and not (out_of_attempts):
if counter < attempts:
login = input ("now password please: ")
counter += 1
else:
out_of_attempts = True
if out_of_attempts:
print ("sorry password limit exceeded, try again later")
else:
print ("thank you please wait")
Upvotes: 0
Views: 1079
Reputation: 2607
Simple slightly more secure way that allows you to store more than just passwords
import hashlib
db = {}
hash = lambda x: hashlib.md5(x.encode()).hexdigest()
def register(user, password, mail):
db[user] = {"password": hash(password), "mail": mail}
def login(user, password):
if db[user]["password"] == hash(password):
print("success!")
else:
print("fail")
register("ironkey", "password123", "[email protected]")
login("ironkey", "password")
login("ironkey", "password123")
# get credentials for the user ironkey
print(db["ironkey"])
fail
success!
{'password': '482c811da5d5b4bc6d497ffa98491e38', 'mail': '[email protected]'}
Upvotes: 0
Reputation: 2682
The equivalent 'mapping' of your usernames/passwords can be done as:
credentials = {
'amy': 'apple',
'chris': 'orange',
'jake': 'date',
}
These allow you to quick 'checks' such as: username in credentials
(return True
or False
) to see if a username has a password; get the password for a given username with credentials[username]
, etc.
Upvotes: 0
Reputation: 15478
Yeah, a dictionary setup will be better:
auth = {'amy': 'apple'....
And so on. Code modification would not be so hard. To get the password of an user (use this to set too)
auth[login]
Upvotes: 1