Python用list和dict实现简单的用户管理系统(增、删、改、查)

#更新用户ID数组
def updateUserIDs():
    global userIds
    userIds = []
    for i in userList:
        userIds.append(i['id'])

#添加用户
def addUser():
    print('当前用户编号:')
    print(userIds)
    user = {};
    while True:
        userId = int(input('请输入添加用户的编号:'))
        if userId in userIds:
            print('您输入的用户编号已存在!请重新输入')
        else:
            user['id'] = userId
            user['name'] = input('请输入用户名:')
            user['pw'] = input('请输入密码:')
            userList.append(user)
            print('添加用户成功!')
            print()
            updateUserIDs()
            break

#删除用户
def delUser():
    print('当前用户编号:')
    print(userIds)
    while True:
        userId = int(input('请输入想要删除的用户编号:'))
        if userId in userIds:
            for user in userList:
                if user.get('id')==userId:
                    userList.remove(user)
                    updateUserIDs()
                    print('删除成功')
                    print()
            break
        else:
            print('输入的用户编号有误,请核对!')
    
#修改用户
def updateUser():
    print('当前用户编号:')
    print(userIds)
    while True:
        userId = int(input('请输入修改用户的编号'))
        if userId in userIds:
            for user in userList:
                if user['id'] == userId:
                    user['name'] = input('请输入姓名:')
                    user['pw'] = input('请输入密码:')
                    updateUserIDs()
                    print('用户信息修改成功!')
            print()
            break
        else:
            print('输入的用户编号有误,请核对!')

#查询用户
def findUser():
    print('当前用户编号:')
    print(userIds)
    while True:
        userId = int(input('请输入查找用户的编号'))
        if userId in userIds:
            for user in userList:
                if user['id'] == userId:
                    print('查找用户信息为:')
                    print('name:',user['name'])
                    print('password:',user['pw'])
                    print()
            break
        else:
            print('输入的用户编号有误,请核对!')
#查询全部
def allUser():
    print('id\tname\tpassword')
    for user in userList:
        print(str(user['id'])+'\t'+user['name']+'\t'+user['pw'])
    print


user1 = {'id':2, 'name':'张三1', 'pw':'123'}
user2 = {'id':23, 'name':'张三2', 'pw':'456'}
user3 = {'id':21, 'name':'张三3', 'pw':'789'}

userList = [user1, user2, user3]
userIds = []

for i in userList:
    userIds.append(i['id'])

menuIds = [1,2,3,4,5,6]
menuList = ["添加用户","删除用户","修改用户","查询用户","查询全部","退出"]

while True:
    print('欢迎来到用户管理系统')
    for i in range(len(menuIds)):
        print('\t',menuIds[i],menuList[i])
    choice = int(input('请输入序号进行选择:'))
    if choice == 1:
        addUser()
    elif choice == 2:
        delUser()
    elif choice == 3:
        updateUser()
    elif choice == 4:
        findUser()
    elif choice == 5:
        allUser()
    elif choice == 6:
        print('欢迎下次使用')
        break
    else:
        print('输入序号有误')
posted @ 2019-12-13 18:04  羽吢  阅读(684)  评论(0编辑  收藏  举报