MST

星途 面试题库

面试题:Python中if语句错误处理与复杂逻辑结合

编写一个Python程序,要求实现如下功能:有一个列表存储了一些字典,每个字典有'name'和'age'字段。程序接收用户输入一个字符串,如果字符串在某个字典的'name'中匹配,判断对应'age'是否大于18,若大于18则打印'成年',否则打印'未成年';如果没有匹配到,则打印'未找到'。要妥善处理在获取和判断数据过程中可能出现的各种错误,包括输入类型错误、字典结构异常等,给出详细代码及注释。
27.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def check_age():
    # 定义存储字典的列表
    person_list = [
        {'name': 'Alice', 'age': 20},
        {'name': 'Bob', 'age': 16}
    ]
    try:
        # 获取用户输入
        input_str = input("请输入字符串: ")
        # 标记是否找到匹配
        found = False
        for person in person_list:
            # 检查字典结构是否正确
            if not isinstance(person, dict) or 'name' not in person or 'age' not in person:
                continue
            if input_str in person['name']:
                found = True
                try:
                    age = int(person['age'])
                    if age > 18:
                        print('成年')
                    else:
                        print('未成年')
                except (ValueError, TypeError):
                    print('年龄数据异常')
                break
        if not found:
            print('未找到')
    except (EOFError, KeyboardInterrupt):
        print('输入中断')
    except Exception as e:
        print(f'发生错误: {e}')


if __name__ == "__main__":
    check_age()