Python Usernames and Passwords

user547853 picture user547853 · Dec 19, 2010 · Viewed 18.6k times · Source

I am trying to create a program in which you can create, log in, and delete accounts. I have made 2 lists, one with usernames and one with passwords. The script asks for an input and if you say log in, it says:

if loginchoice=='login':
    choice = raw_input("What is your username? ")
    choice2 = raw_input("What is your password? ")
    if choice in accounts:
        option1=1
    else:
        option1=0
    if choice2 in password:
        option2=1
    else:
        option2=0
    if option1==1 and option2==1:
        print "Welcome to Telemology,", choice
    else:
        print "The username or password you entered is incorrect. Please try again or register."

As you can see, it only checks to see if the inputs are already in the lists. It doesn't see if the inputs have the same index. I can't put "accounts.index(choice)" because it treats 'choice' as an integer. The same goes for quotations because of strings. It doesn't treat them as variables. Is there any way around this?

I hope that if my question gets answered, two people won't register simultaneously and glitch the indices.

Answer

9000 picture 9000 · Dec 19, 2010

What you want is a mapping, or a dictionary. Its key would be username, its contents the password for that username.

users = {} # this is the mapping
users["joe"] = "123" # it currently contains username "joe" with password "123"
...
username = raw_input("What is your username? ")
password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users[username]
  if expected_password == password:
    print "Welcome to Telemology,", username
  else:
    print "Didn't you forget your password,", username
else:
  print "Unknown user"

Of course, in a real system you'd store passwords salted and encrypted.