Welcome, guest | Sign In | My Account | Store | Cart

Just a simple login that uses a dictionary. Don't know if it would work on a console. Plus I can't figure out a way to add something to the dictionary while the program is running.

Python, 7 lines
1
2
3
4
5
6
7
database={'name': '1234', 'name2': '5678', 'name3': '9012'}
name = raw_input('Enter username: ')
ask = raw_input('Enter pin: ')
if ask in database[name]:
    print 'Welcome', name
else:
    print 'Invalid code'

2 comments

Charlie Clark 14 years, 8 months ago  # | flag

A couple of comments: first of all you seem to be starting out in Python so a mailing list or a forum might be a better place for this. Secondly, you are just checking for the password against a string using "in" which will be true for '1' or '2' or '3' or '4' for your first user. In fact passwords should never be stored unencrypted and usually a "salt" is added to the encryption to obfuscate the result of hash function. For the same reason, we don't want to let a hacker know if they have the right username but not the right password, an error is usually returned if either is incorrect and errors are best reported by raising an exception. You might like to use the following as a starting point for further exploration.

import hashlib

database={'name': '1234', 'name2': '5678', 'name3': '9012'}
encrypted = dict([(name, hashlib.md5(pw).hexdigest()) for name, pw in database.items()])

name = raw_input('Enter username: ')
ask = raw_input('Enter pin: ')

if name not in encrypted \
      or hashlib.md5(ask).hexdigest() != encrypted.get(name):
   raise ValueError("Username or password incorrect")
else:
   print("Welcome %s" % name)
Larry Hastings 14 years, 8 months ago  # | flag

What he said. Recipes should be interesting or novel or solve difficult problems. This is beginner stuff, and it's simply bad code. I'm not trying to get on your case for being a beginner--but if you're a beginner, you aren't ready to post examples.

Problems with this code:

  1. If the user types a "name" that is not in the "database", the program crashes.
  2. "if x in y" means "does x appear anywhere in y". Since database only contains strings, "if ask in database[name]" means "does the string 'ask' appear anywhere in the string 'database[name]'". Therefore, if the user types in no password, they pass the check.
  3. As pointed out, storing plaintext passwords is naughty.

To add new things to a dictionary while the program is running, try something like the following:

database = {}
database["name"] = "1234"

Good luck with Python, and I hope to see you back here when you have something more interesting to share.

Created by Christopher Scott on Mon, 6 Jul 2009 (MIT)
Python recipes (4591)
Christopher Scott's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks