小姐姐学Python-class3-2

使用字典完成登录的demo

廖雪峰的博客中学习基本的字典操作后,完成一个小型的demo,用字典存储用户的信息,然后模拟登录的操作。

要求:
1. 理解每行代码的含义,熟悉字典的get,[0]中括号索引等方式的取值。
2. 更改代码,实现三次输入密码错误,则结束程序,否则提示登录成功。

代码:


# l = [{'a':1},{'b':2}] # print(l[0]) table = { 'user': [ { 'name':'administrator', 'age':22, 'height':213, 'weight':100, 'username':'admin', 'password':'123456' }, { 'name':'hashiqi', 'age':18, 'height':188, 'weight':50, 'username':'doge', 'password':'666666' }, ], 'company':{ 'name':'BAT', 'url':'www.baidu.com' } } # print(table.get('user')[1].get('name')) username = input('please input your username\n') password = input('please input your password\n') users = table.get('user') find = False for user in users: if user.get('username') == username: if user.get('password') != password: print('password wrong !') break print('welcome !',username) print('your infomation is showing below !') print(user) find = True break if find == False: print("Login fail")

要求2答案:

要求2的答案:
def login():
    dic = {
        'wenjun':'wenjun',
        'liuyang':'123456'
    }
    account = ''
    password = ''

    # for i in range(1,10):

    # for i in [1,2,3,4,5,6,7,8,9]

    try_time = 3
    while try_time > 0:
        account = input('请输入账号')
        password = input('请输入密码')
        for k,v in dic.items():
            if k == account and v == password:
                print('登录成功,欢迎: %s' % account)
                return True
        try_time -= 1
        print('账号或者密码错误,你还有 ',try_time,'次机会')

    print('登录失败')
    return False

login()

点赞
  1. 图图说道:

    :cool: 很好,受益终生的好帖子