一、什么是逻辑运算符?
逻辑运算符用于连接多个条件,返回布尔值(True或False)。就像日常说话中的“并且”、“或者”、“不”。
# 逻辑运算符示例age = 25has_id = True# 并且:两个条件都满足if age >= 18and has_id:print("可以进入")# 或者:满足一个条件即可if age < 12or age > 60:print("可以优惠")# 不:取反ifnot has_id:print("没有身份证")
二、3种基本逻辑运算符
| | | | |
and | | True and False | False | |
or | | True or False | True | |
not | | not True | False | |
三、and(逻辑与)
3.1 真值表
| | |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
3.2 基本用法
# 两个条件都满足才为Trueage = 25score = 85print(age >= 18and score >= 60) # True and True → Trueprint(age >= 18and score >= 90) # True and False → Falseprint(age < 18and score >= 60) # False and True → False# 实际应用:判断是否可以毕业passed_all = Trueno_debt = Trueif passed_all and no_debt:print("可以毕业") # 会执行else:print("不能毕业")
3.3 多个条件连接
# 三个条件同时满足x = 5print(x > 0and x < 10and x != 3) # True# 可以换行提高可读性if (age >= 18and has_id andnot is_blacklisted):print("验证通过")
3.4 短路求值
# and左边为False,右边不执行defcheck_right():print("右边函数被调用")returnTrueresult = Falseand check_right() # check_right不会执行print(result) # False# 实际应用:避免除零错误x = 0y = 10if x != 0and y / x > 5: # x=0时,右边不会执行,避免报错print("条件成立")else:print("条件不成立")
四、or(逻辑或)
4.1 真值表
| | |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
4.2 基本用法
# 只要一个条件满足就为Trueis_vip = Falseis_holiday = Trueprint(is_vip or is_holiday) # False or True → Trueprint(is_vip orFalse) # False or False → False# 实际应用:优惠条件if is_vip or is_holiday or age < 12:print("享受优惠")else:print("原价")
4.3 多个条件连接
# 多个or条件role = "admin"print(role == "admin"or role == "manager"or role == "owner") # True# 更简洁的写法allowed_roles = ["admin", "manager", "owner"]print(role in allowed_roles) # 同上
4.4 短路求值
# or左边为True,右边不执行defcheck_right():print("右边函数被调用")returnTrueresult = Trueor check_right() # check_right不会执行print(result) # True# 实际应用:设置默认值name = input("请输入名字:") or"匿名用户"print(f"你好,{name}") # 如果输入为空,就用"匿名用户"
五、not(逻辑非)
5.1 真值表
5.2 基本用法
# 取反is_rain = Falseprint(not is_rain) # Trueis_logged_in = Trueprint(not is_logged_in) # False# 实际应用ifnot is_rain:print("可以去跑步") # 不会下雨就去ifnot is_logged_in:print("请先登录")
5.3 双重否定
# 双重否定等于肯定x = Trueprint(notnot x) # Truey = Falseprint(notnot y) # False# 实际应用:转换为布尔值value = "hello"print(notnot value) # True(非空字符串)print(notnot"") # False(空字符串)
5.4 与in连用
# 检查不在列表中fruits = ["apple", "banana", "orange"]fruit = "grape"if fruit notin fruits: # 等价于 not (fruit in fruits)print(f"{fruit}不在列表中")# 检查不是空text = ""ifnot text:print("字符串为空")
六、逻辑运算符的优先级
# 优先级:not > and > orresult = TrueorFalseandFalse# 等价于:True or (False and False)# True or False → Trueprint(result) # True# 用括号提高可读性result = (TrueorFalse) andFalse# True and False → Falseprint(result) # False# not优先级最高result = notTrueandFalse# (not True) and False → False and False → Falseprint(result) # False
七、逻辑运算符的返回值
7.1 and的返回值
# and返回最后一个计算的值print(1and2) # 2(不是True)print(0and2) # 0(左边假,返回左边)print(1and2and3) # 3(都真,返回最后一个)# 实际应用:安全取值user = {"name": "张三", "age": 25}age = user.get("age") and user["age"] + 1print(age) # 26
7.2 or的返回值
# or返回第一个真值print(1or2) # 1print(0or2) # 2print(0orFalseor3) # 3# 实际应用:默认值name = input("请输入名字:") or"匿名"print(name)
7.3 实际应用技巧
# 选择第一个非空值a = Noneb = ""c = "Hello"d = "World"result = a or b or c or dprint(result) # "Hello"# 带默认值的函数参数defgreet(name=None): name = name or"朋友"print(f"你好,{name}")greet() # 你好,朋友greet("张三") # 你好,张三
八、实战案例
案例1:登录验证系统
deflogin_system():"""登录验证系统"""# 用户数据 users = {"admin": "123456","user1": "abc123","test": "test123" }print("=" * 40)print(" 用 户 登 录")print("=" * 40)# 输入 username = input("用户名:").strip() password = input("密码:").strip()# 验证逻辑(使用逻辑运算符)ifnot username ornot password:print("❌ 用户名和密码不能为空")returnFalseif username notin users:print("❌ 用户不存在")returnFalseif users[username] != password:print("❌ 密码错误")returnFalse# 附加条件 is_admin = username == "admin" is_weekend = False# 假设不是周末print(f"\n✅ 登录成功!欢迎{username}")if is_admin or is_weekend:print("✨ 管理员权限或周末登录,获得双倍积分")# 密码强度提醒iflen(password) < 6or password.isdigit() or password.isalpha():print("⚠️ 建议:您的密码强度较弱,建议修改")returnTrue# login_system()
案例2:商品促销判断
defcheck_promotion(price, quantity, is_vip, is_holiday, is_first_buy):"""判断商品促销条件"""print(f"\n商品单价:{price}元,购买数量:{quantity}")print(f"VIP会员:{'是'if is_vip else'否'}")print(f"节假日:{'是'if is_holiday else'否'}")print(f"首次购买:{'是'if is_first_buy else'否'}")print("-" * 30) total = price * quantity promotions = []# 条件1:满减优惠(满足一个即可)if total >= 200or (is_vip and total >= 150): promotions.append("满200减30(或VIP满150减30)") discount = 30elif total >= 100or is_first_buy: promotions.append("满100减10(或首购满100减10)") discount = 10else: discount = 0# 条件2:节假日双倍积分if is_holiday and total >= 50: points = int(total) * 2 promotions.append(f"节假日双倍积分:{points}")else: points = int(total) if total >= 50else0# 条件3:VIP额外折扣if is_vip andnot is_holiday: # VIP且非节假日 promotions.append("VIP额外95折") total *= 0.95# 条件4:多件折扣if quantity >= 5and total >= 100: promotions.append("5件以上再打9折") total *= 0.9# 输出结果if promotions:print("获得优惠:")for p in promotions:print(f" ✅ {p}")else:print("❌ 没有符合条件的优惠")print(f"\n最终金额:{total:.2f}元")return total# 测试各种组合check_promotion(45, 3, True, False, False) # VIP,非节假日check_promotion(25, 5, False, True, True) # 非VIP,节假日,首购check_promotion(30, 2, False, False, False) # 无任何优惠
案例3:密码强度检测
defcheck_password_strength(password):"""检测密码强度(使用逻辑运算符)"""ifnot password:return"密码不能为空", 0# 各种条件判断 length_ok = len(password) >= 8 has_upper = any(c.isupper() for c in password) has_lower = any(c.islower() for c in password) has_digit = any(c.isdigit() for c in password) has_symbol = any(not c.isalnum() for c in password)# 使用逻辑运算符组合条件 very_strong = length_ok and has_upper and has_lower and has_digit and has_symbol strong = length_ok and ((has_upper and has_lower) or (has_digit and has_symbol)) medium = length_ok or (has_upper and has_lower and has_digit)# 判断强度if very_strong: level = "非常强" score = 5 advice = "密码很安全"elif strong: level = "强" score = 4 advice = "密码强度良好"elif medium: level = "中等" score = 3 advice = "可以增加特殊字符提高强度"elif length_ok or has_upper or has_lower or has_digit: level = "弱" score = 2 advice = "密码太简单,建议增加长度和字符类型"else: level = "非常弱" score = 1 advice = "密码不符合基本要求"# 给出具体建议 suggestions = []ifnot length_ok: suggestions.append("长度至少8位")ifnot (has_upper and has_lower): suggestions.append("同时包含大小写字母")ifnot has_digit: suggestions.append("包含数字")ifnot has_symbol: suggestions.append("包含特殊字符")return level, score, advice, suggestions# 测试passwords = ["123", "abc123", "Abc123", "Abc123!@", "Abc123!@#$"]for pwd in passwords: level, score, advice, suggestions = check_password_strength(pwd)print(f"\n密码:{pwd:15} 强度:{level}({score}/5)")print(f"建议:{advice}")if suggestions:print(f"改进:{', '.join(suggestions)}")
案例4:表单验证器
defvalidate_form(data):"""表单验证(使用逻辑运算符)""" errors = [] warnings = []# 必填字段验证 required_fields = ['username', 'email', 'age', 'password']for field in required_fields:ifnot data.get(field): # 空值检查 errors.append(f"{field}不能为空")# 如果有错误,直接返回if errors:returnFalse, errors, warnings username = data['username'] email = data['email'] age = data['age'] password = data['password']# 用户名验证iflen(username) < 3orlen(username) > 20: errors.append("用户名长度必须在3-20之间")elifnot (username.isalnum() or'_'in username): errors.append("用户名只能包含字母、数字和下划线")# 邮箱验证(简单的逻辑组合)if'@'notin email or'.'notin email: errors.append("邮箱格式不正确")elif email.count('@') != 1or email.startswith('@') or email.endswith('.'): errors.append("邮箱格式不正确")# 年龄验证try: age = int(age)if age < 0or age > 150: errors.append("年龄必须在0-150之间")elif age < 18or age > 100: warnings.append("年龄不在常规范围,请确认")except ValueError: errors.append("年龄必须是数字")# 密码验证iflen(password) < 6: errors.append("密码至少6位")else:# 密码强度警告ifnot (any(c.isupper() for c in password) andany(c.islower() for c in password) andany(c.isdigit() for c in password)): warnings.append("密码强度较弱,建议包含大小写字母和数字")# 返回结果if errors:returnFalse, errors, warningselif warnings:returnTrue, ["验证通过(有警告)"], warningselse:returnTrue, ["验证完全通过"], []# 测试test_data = [ {"username": "张三", "email": "zhangsan@test.com", "age": "25", "password": "Abc123"}, {"username": "a", "email": "invalid", "age": "200", "password": "123"}, {"username": "user_123", "email": "user@test.com", "age": "16", "password": "abc123"}, {}]for data in test_data: valid, messages, warnings = validate_form(data)print(f"\n数据:{data}")print(f"结果:{'✅ 通过'if valid else'❌ 拒绝'}")for msg in messages:print(f" {msg}")for warn in warnings:print(f" ⚠️ {warn}")
案例5:权限控制系统
classPermissionSystem:"""权限控制系统"""def__init__(self):self.users = {"admin": {"role": "admin", "permissions": ["read", "write", "delete", "manage"]},"manager": {"role": "manager", "permissions": ["read", "write", "delete"]},"user1": {"role": "user", "permissions": ["read"]},"guest": {"role": "guest", "permissions": []} }self.resources = {"public": {"level": "public", "owner": None},"docs": {"level": "protected", "owner": "manager"},"config": {"level": "private", "owner": "admin"},"secrets": {"level": "top_secret", "owner": "admin"} }defcheck_permission(self, username, resource, action):"""检查权限(使用逻辑运算符)"""# 用户是否存在if username notinself.users:returnFalse, "用户不存在"# 资源是否存在if resource notinself.resources:returnFalse, "资源不存在" user = self.users[username] res = self.resources[resource]# 超级管理员权限(最高优先级)if user["role"] == "admin"and action in user["permissions"]:returnTrue, "超级管理员权限"# 资源所有者权限if res["owner"] == username and action in ["read", "write"]:returnTrue, "资源所有者权限"# 公共资源访问if res["level"] == "public"and action == "read":returnTrue, "公共资源可读"# 角色基础权限if action in user["permissions"]:# 特定资源限制if res["level"] == "top_secret"and user["role"] != "admin":returnFalse, "绝密资源仅限管理员"if res["level"] == "private"and user["role"] notin ["admin", "manager"]:returnFalse, "私有资源权限不足"returnTrue, "权限允许"returnFalse, "权限不足"# 测试ps = PermissionSystem()# 测试各种组合tests = [ ("admin", "secrets", "read"), # 管理员读绝密 ("manager", "secrets", "read"), # 经理读绝密 ("user1", "public", "read"), # 用户读公共 ("user1", "docs", "write"), # 用户写文档 ("guest", "public", "read"), # 访客读公共 ("admin", "config", "manage"), # 管理员管理配置]for username, resource, action in tests: allowed, reason = ps.check_permission(username, resource, action) result = "✅ 允许"if allowed else"❌ 拒绝"print(f"{username:8}{action:6}{resource:10} → {result}({reason})")
九、常见错误与注意事项
错误1:误用位运算符
# ❌ 错误:用 & 代替 andx = True & False# 这是位运算,不是逻辑运算print(x) # 0(不是False)# ✅ 正确x = TrueandFalseprint(x) # False
错误2:混淆and和or
# 容易混淆的场景x = 5# 想表达:x在1到10之间if x > 1and x < 10: # ✅ 正确passif x > 1or x < 10: # ❌ 错误,永远为Truepass
错误3:优先级问题
# 忘记加括号x = 5y = 10# 想表达:(x > 3) and (y < 20) or (x == 5)if x > 3and y < 20or x == 5: # 等价于 (x>3 and y<20) or (x==5)pass# 加括号更清晰if (x > 3and y < 20) or (x == 5):pass
错误4:链式比较替代
# Python可以用链式比较替代andx = 5# ✅ 更Pythonic的方式if1 < x < 10:print("x在1-10之间")# 等价于if x > 1and x < 10:print("x在1-10之间")
十、逻辑运算符速查表
| | | |
and | | T and T = TT and F = FF and T = FF and F = F | |
or | | T or T = TT or F = TF or T = TF or F = F | |
not | | not T = F | |
十一、记忆口诀
逻辑运算符三个and or 和 notand就像串连电路两个开关都要通一个不通就不亮全部通才亮起来or就像并联电路一个开关就能亮两个都不通才灭一个通就亮起来not就是个反相器真变假来假变真短路求值要记牢and左边假停住or左边真停住提高效率不犯错优先级要分清not最高 and次之or最低用括号可读性最重要