Python字典用法例子

2011-05-19  李琪 

#-*- coding:utf-8 -*-
'''
Created on 2011-5-15
作者: 李昱彤
Email: liqi1031@gmail.com
'''
db = {}
def newUser():
    prompt = 'login desired: '
    while True:
        name = raw_input(prompt)
        pwd = raw_input('password: ')
       
        if len(name) == 0 or len(pwd) == 0:
            print '\nUser name and password can not be empty!'
            continue
        else:
            break
           
        if db.has_key(name):
            prompt = '%s taken, try another: ' % name
            continue
        else:
            break
       
    db[name] = pwd
    print '\nThe user %s is created with password %s' % (name, pwd)
   
def oldUser():
    name = raw_input('login: ')
    pwd = raw_input('password: ')
    passwd = db.get(name)
    if passwd == pwd:
        pass
    else:
        print 'login incorrect.'
        return
   
    print 'Welcome back %s' % name
   
def showMenu():
    prompt = '''
    (N)ew User Login
    (E)xisting User Login
    (Q)uit
Enter your choice: '''
   
    done = False
    while not done:
        chosen = False
        while not chosen:
            try:
                choice = raw_input(prompt)[0]
            except (EOFError, KeyboardInterrupt):
                choice = 'q'
            print '\nYou picked: [%s]' % choice.upper()
            if choice not in 'nNeEqQ':
                print 'invalid option, try again'
            else:
                chosen = True
           
            if choice == 'q':
                done = True
                print 'Quit now!'
            if choice == 'n' or choice == 'N': newUser()
            if choice == 'e' or choice == 'E': oldUser()
           
if __name__ == '__main__':
    showMenu()
 
371°/3715 人阅读/0 条评论 发表评论

登录 后发表评论