You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现用户名与对应索引设备ID匹配验证的问题求助

问题分析与代码修正

原代码的核心问题

  • 输入的设备ID是字符串类型,但device_id列表存储的是整数,直接调用device_id.index(device)会因类型不匹配抛出ValueError,导致程序崩溃。
  • 先执行index()方法再做存在性检查:如果输入的用户名或设备ID不在列表中,程序会直接报错,无法进入后续的权限判断逻辑。
  • 逻辑关联错误:即便用户名和设备ID都在各自列表中,但未通过索引绑定两者的对应关系,导致只要两者都合法就会误判为有权限。

修正后的代码

approved_users = ['Chad', 'Tina', 'Jared', 'Lars', 'Henry', 'Jasmine']
device_id = [127, 416, 709, 358, 672, 939]

user = input('Enter your username: ')
# 处理设备ID输入:转为整数并捕获格式错误
try:
    device = int(input('Enter your device id: '))
except ValueError:
    print("Invalid device ID format. Please enter a numeric ID.")
    exit()

# 先验证用户名是否在白名单中
if user in approved_users:
    user_idx = approved_users.index(user)
    # 对比该用户名对应索引的设备ID
    if device_id[user_idx] == device:
        print(f"{user} has access to the system with device ID: {device}")
    else:
        print(f"{user} is an approved user, but the provided device ID is not associated with your account.")
else:
    print(f"Username {user} is not in the approved list.")

改动说明

  • 类型兼容处理:将设备ID输入转为整数,同时用try-except处理非数字输入的情况,避免程序崩溃。
  • 逻辑流程优化:先确认用户名合法,再通过索引获取其对应的绑定设备ID,直接对比输入值,确保只有配对正确的组合才能通过验证。
  • 精准错误提示:分场景给出不同的错误信息,帮助用户快速定位问题。

内容的提问来源于stack exchange,提问作者Mobile App Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 17:01:01