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

Python条件判断函数调试求助:双列表授权逻辑问题

调试你的授权函数

核心问题分析

你的代码主要在条件判断的语法和逻辑上出了问题,以下是具体错误点和修正方案:

原代码的错误点:

  1. 第一个if条件逻辑错误:
    原写法name.lower() in (omaha_location) and (list_names)中,and (list_names)是判断列表是否非空,而非判断名字是否在list_names里,正确逻辑应该是同时判断名字在两个列表中。
  2. 第二个elif条件语法完全错误:
    name.islower()返回的是布尔值(True/False),不是小写后的名字;同时in list_names not in omaha_location的逻辑结构不符合Python语法,需要拆分成两个独立的判断并用and连接。
  3. 字符串拼接缺少空格:
    比如f'{name}this is not your location...'会导致输出无空格的拼接结果(如ladythis is...),需要添加空格。

修正后的完整代码

def authorization(name):
    # 统一转小写,避免大小写匹配问题
    lower_name = name.lower()
    
    # 条件1:名字同时在两个列表中
    if lower_name in list_names and lower_name in omaha_location:
        return f"Hello {name}, you are authorized"
    
    # 条件2:名字在list_names但不在omaha_location
    elif lower_name in list_names and lower_name not in omaha_location:
        return f"{name}, this is not your location, please see HR"
    
    # 条件3:其他情况
    else:
        return f"Hello {name}, you are not authorized!"

name = input("Please enter your name: ")
list_names = ['dan','kyle','lady','luna']
omaha_location = ['dan','kyle']
print(authorization(name))

额外优化建议

  • 把list_names和omaha_location作为参数传入函数,避免依赖全局变量,让函数更通用:
    def authorization(name, valid_names, location_names):
        lower_name = name.lower()
        if lower_name in valid_names and lower_name in location_names:
            return f"Hello {name}, you are authorized"
        # 后续逻辑同理...
    
    # 调用时传入参数
    print(authorization(name, list_names, omaha_location))
    

内容的提问来源于stack exchange,提问作者Kyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:27:16