Python权限验证代码语法错误排查:无法按输入输出正确结果
解决Python权限验证代码的语法错误与逻辑问题
问题分析
- 语法错误根源:第4行的
is in是非法Python语法,判断元素是否存在于序列(如元组)中,正确的运算符是单独的in,无需添加is。 ==运算符无效的原因:==用于判断两个值是否完全相等,你这里需要验证输入姓名是否属于authorized_users元组中的成员,用==会把输入内容和整个元组做比较,必然不相等,因此无法得到预期结果。
修复后的完整代码
authorized_users = ("Sheldon", "Mark", "Daniel") user_input = input("Please enter your name: ") if user_input in authorized_users: print("Access Granted!") print(f"Hello {user_input}!") else: print("Access Denied!")
额外优化建议
如果需要忽略输入的大小写(比如用户输入sheldon或SHELDON也能通过验证),可以对输入内容做标准化处理后再判断:
authorized_users = ("Sheldon", "Mark", "Daniel") user_input = input("Please enter your name: ").strip().title() if user_input in authorized_users: print("Access Granted!") print(f"Hello {user_input}!") else: print("Access Denied!")
内容的提问来源于stack exchange,提问作者Programmer96
相关产品推荐
相关产品推荐

