MST

星途 面试题库

面试题:Python嵌套if语句中的代码优化

给定一段使用嵌套if语句来处理用户权限的代码(如下),存在一些可以优化的地方,请指出并进行优化。 ```python user_role = input('请输入用户角色(admin, editor, guest):') if user_role == 'admin': action = input('请输入操作(create, read, update, delete):') if action == 'create': print('管理员有权创建') elif action =='read': print('管理员有权读取') elif action == 'update': print('管理员有权更新') elif action == 'delete': print('管理员有权删除') else: print('无效操作') elif user_role == 'editor': action = input('请输入操作(create, read, update):') if action == 'create': print('编辑有权创建') elif action =='read': print('编辑有权读取') elif action == 'update': print('编辑有权更新') else: print('无效操作') elif user_role == 'guest': action = input('请输入操作(read):') if action =='read': print('访客有权读取') else: print('无效操作') else: print('无效角色') ```
23.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 指出可优化点
    • 代码中存在大量重复的if - elif - else结构来处理不同用户角色的操作,代码冗余度较高。
    • 每次获取用户输入的操作时,没有对输入进行有效性检查,如果用户输入的操作不符合提示的范围,只能在后续的if - elif - else结构中判断为无效操作,不够友好。
  2. 优化后的代码
role_actions = {
    'admin': ['create','read', 'update', 'delete'],
    'editor': ['create','read', 'update'],
    'guest': ['read']
}

user_role = input('请输入用户角色(admin, editor, guest):')
if user_role not in role_actions:
    print('无效角色')
else:
    valid_actions = role_actions[user_role]
    action = input(f'请输入操作({", ".join(valid_actions)}):')
    if action not in valid_actions:
        print('无效操作')
    else:
        role_map = {
            'admin': '管理员',
            'editor': '编辑',
            'guest': '访客'
        }
        print(f'{role_map[user_role]}有权{action}')

在优化后的代码中:

  • 首先定义了一个字典role_actions,用来存储不同用户角色对应的有效操作。这样可以通过字典查询直接获取用户角色对应的操作列表,避免了重复的if - elif - else结构。
  • 在获取用户输入的操作前,先根据用户角色获取有效操作列表,并将其显示给用户,同时检查用户输入的操作是否在有效操作列表内,提高了用户输入的友好性和程序的健壮性。
  • 使用一个字典role_map来映射用户角色和对应的中文描述,用于输出更友好的提示信息。