第14课:逻辑小侦探——and、or、not
🎯 本课目标
- 掌握逻辑运算符
and、or、not的用法 - 理解逻辑运算的真值表
- 学会组合多个条件判断
- 在实际问题中应用逻辑运算
- 制作复杂的判断程序
🔍 趣味引入:成为逻辑小侦探
想象一下:你是一个小侦探,需要解决各种谜题:
- 🎒 书包里有铅笔并且有橡皮
- 🍎 吃苹果或者吃香蕉
- 🚫 不是周末的时候要上学
- 📚 完成语文作业并且数学作业
这些"并且"、"或者"、"不"就是逻辑运算符!今天,让我们一起成为逻辑小侦探,学习如何用代码做复杂的判断!
🔧 第一部分:认识逻辑运算符
1.1 逻辑运算符是什么?
# 逻辑运算符
print("🔍 认识逻辑运算符")
print("=" * 30)
# 三个逻辑运算符
print("1. and - 并且(两个条件都要满足)")
print("2. or - 或者(满足一个条件就行)")
print("3. not - 不(取反,真的变假,假的变真)")
print()
# 简单示例
is_sunny = True
is_weekend = False
print(f"天气晴朗:{is_sunny}")
print(f"是周末:{is_weekend}")
print()
# 使用逻辑运算符
can_play = is_sunny and is_weekend
print(f"能出去玩吗?(天气好并且是周末)")
print(f" is_sunny and is_weekend = {is_sunny} and {is_weekend} = {can_play}")
1.2 基本逻辑运算
# 基本逻辑运算
print("\n🧮 基本逻辑运算")
print("=" * 30)
# 定义两个布尔值
a = True
b = False
print(f"a = {a}, b = {b}")
print()
# 1. and 运算
and_result = a and b
print(f"1. a and b = {a} and {b} = {and_result}")
# 2. or 运算
or_result = a or b
print(f"2. a or b = {a} or {b} = {or_result}")
# 3. not 运算
not_a = not a
not_b = not b
print(f"3. not a = not {a} = {not_a}")
print(f"4. not b = not {b} = {not_b}")
📊 第二部分:真值表学习
2.1 真值表理解
# 真值表学习
print("📊 逻辑运算真值表")
print("=" * 40)
# 所有可能的布尔值组合
values = [(True, True), (True, False), (False, True), (False, False)]
print("a b a and b a or b not a not b")
print("-" * 50)
for a, b in values:
and_result = a and b
or_result = a or b
not_a = not a
not_b = not b
print(f"{a:^6} {b:^6} {and_result:^9} {or_result:^8} {not_a:^7} {not_b:^7}")
# 记忆技巧
print(f"\n💡 记忆技巧:")
print(" and:两个都为True,结果才是True")
print(" or: 只要有一个为True,结果就是True")
print(" not:真的变假,假的变真")
2.2 真值表游戏
# 真值表游戏
print("\n🎮 真值表填空游戏")
print("=" * 30)
# 题目
questions = [
("True and True = ", True and True, True),
("True and False = ", True and False, False),
("False and True = ", False and True, False),
("False and False = ", False and False, False),
("True or True = ", True or True, True),
("True or False = ", True or False, True),
("False or True = ", False or True, True),
("False or False = ", False or False, False),
("not True = ", not True, False),
("not False = ", not False, True)
]
score = 0
print("请填写逻辑运算的结果(True/False):")
for i, (question, result, correct) in enumerate(questions, 1):
print(f"\n{i}. {question}", end="")
try:
answer = input().strip()
# 处理不同输入
if answer.lower() in ['true', 't', '是', 'yes', 'y', '1']:
user_bool = True
elif answer.lower() in ['false', 'f', '否', 'no', 'n', '0']:
user_bool = False
else:
raise ValueError
if user_bool == correct:
print(" ✅ 正确!")
score += 1
else:
print(f" ❌ 错误!正确答案是:{correct}")
except:
print(f" ❌ 请输入True或False!正确答案是:{correct}")
print(f"\n📊 得分:{score}/{len(questions)}")
if score == len(questions):
print("🎉 真值表大师!")
elif score >= len(questions) * 0.8:
print("👍 很棒!几乎全对!")
else:
print("💪 多加练习,你会更棒!")
🎯 第三部分:and 运算(并且)
3.1 and 运算详解
# and 运算
print("🎯 and 运算(并且)")
print("=" * 30)
print("and:两个条件都要满足,结果才是True")
print()
# 示例:上学条件
has_homework = True
is_healthy = True
is_weekday = True
print("🎒 上学条件检查:")
print(f" 有作业完成:{has_homework}")
print(f" 身体健康:{is_healthy}")
print(f" 是工作日:{is_weekday}")
print()
# 使用 and
can_go_to_school = has_homework and is_healthy and is_weekday
print(f"能去上学吗?(有作业并且健康并且是工作日)")
print(f" {has_homework} and {is_healthy} and {is_weekday} = {can_go_to_school}")
if can_go_to_school:
print("✅ 可以去上学!")
else:
print("❌ 今天不能去上学")
3.2 实际应用:游戏角色条件
# 游戏角色条件
print("\n🎮 游戏角色创建条件")
print("=" * 30)
# 角色属性
age = 12
has_parent_permission = True
has_email = True
password_length = 8 # 密码长度
print("📋 创建游戏账号的条件:")
print(f" 年龄:{age}岁")
print(f" 家长同意:{has_parent_permission}")
print(f" 有邮箱:{has_email}")
print(f" 密码长度:{password_length}位")
print()
# 检查所有条件
condition1 = age >= 10 # 年龄大于等于10岁
condition2 = has_parent_permission # 家长同意
condition3 = has_email # 有邮箱
condition4 = password_length >= 6 # 密码至少6位
can_create_account = condition1 and condition2 and condition3 and condition4
print("🔍 条件检查:")
print(f" 年龄≥10岁:{condition1}")
print(f" 家长同意:{condition2}")
print(f" 有邮箱:{condition3}")
print(f" 密码≥6位:{condition4}")
print()
if can_create_account:
print("🎉 恭喜!可以创建游戏账号!")
else:
print("❌ 抱歉,不满足创建条件")
# 提示不满足的条件
if not condition1:
print(" 💡 需要年满10岁")
if not condition2:
print(" 💡 需要家长同意")
if not condition3:
print(" 💡 需要邮箱")
if not condition4:
print(" 💡 密码至少6位")
🎲 第四部分:or 运算(或者)
4.1 or 运算详解
# or 运算
print("🎲 or 运算(或者)")
print("=" * 30)
print("or:只要有一个条件满足,结果就是True")
print()
# 示例:能吃什么水果
has_apple = False
has_banana = True
has_orange = False
print("🍎 水果选择:")
print(f" 有苹果:{has_apple}")
print(f" 有香蕉:{has_banana}")
print(f" 有橙子:{has_orange}")
print()
# 使用 or
can_eat_fruit = has_apple or has_banana or has_orange
print(f"能吃水果吗?(有苹果或者有香蕉或者有橙子)")
print(f" {has_apple} or {has_banana} or {has_orange} = {can_eat_fruit}")
if can_eat_fruit:
print("✅ 有水果可以吃!")
# 具体能吃哪种
if has_apple:
print(" 🍎 可以吃苹果")
if has_banana:
print(" 🍌 可以吃香蕉")
if has_orange:
print(" 🍊 可以吃橙子")
else:
print("❌ 没有水果可以吃")
4.2 实际应用:课外活动选择
# 课外活动选择
print("\n⚽ 课外活动选择")
print("=" * 30)
# 学生兴趣
likes_sports = True
likes_music = False
likes_art = True
likes_science = False
print("🎯 学生兴趣:")
print(f" 喜欢运动:{likes_sports}")
print(f" 喜欢音乐:{likes_music}")
print(f" 喜欢美术:{likes_art}")
print(f" 喜欢科学:{likes_science}")
print()
# 使用 or 判断是否有兴趣
has_interest = likes_sports or likes_music or likes_art or likes_science
if has_interest:
print("✅ 这个学生有课外活动兴趣!")
# 推荐活动
recommendations = []
if likes_sports:
recommendations.append("🏀 篮球社")
recommendations.append("⚽ 足球社")
if likes_music:
recommendations.append("🎵 合唱团")
recommendations.append("🎻 乐器班")
if likes_art:
recommendations.append("🎨 美术社")
recommendations.append("✏️ 书法班")
if likes_science:
recommendations.append("🔬 科学社")
recommendations.append("🤖 机器人社")
print("💡 推荐活动:")
for rec in recommendations:
print(f" {rec}")
else:
print("🤔 这个学生没有明确的课外活动兴趣")
print("💡 建议尝试不同的活动找到兴趣")
🔄 第五部分:not 运算(不)
5.1 not 运算详解
# not 运算
print("🔄 not 运算(不)")
print("=" * 30)
print("not:真的变假,假的变真")
print()
# 示例:上学判断
is_weekend = True
is_holiday = False
is_sick = True
print("📅 状态检查:")
print(f" 是周末:{is_weekend}")
print(f" 是假期:{is_holiday}")
print(f" 生病了:{is_sick}")
print()
# 使用 not
not_weekend = not is_weekend
not_holiday = not is_holiday
not_sick = not is_sick
print("🔍 not 运算结果:")
print(f" not 周末:{is_weekend} → {not_weekend}")
print(f" not 假期:{is_holiday} → {not_holiday}")
print(f" not 生病:{is_sick} → {not_sick}")
print()
# 综合判断
should_go_to_school = not_weekend and not_holiday and not_sick
print(f"应该去上学吗?(不是周末并且不是假期并且没有生病)")
print(f" {not_weekend} and {not_holiday} and {not_sick} = {should_go_to_school}")
if should_go_to_school:
print("✅ 应该去上学!")
else:
print("❌ 今天不用上学")
if is_weekend:
print(" 📅 因为是周末")
if is_holiday:
print(" 🎉 因为是假期")
if is_sick:
print(" 🤒 因为生病了")
5.2 实际应用:密码安全检查
# 密码安全检查
print("\n🔐 密码安全检查")
print("=" * 30)
# 密码检查
password = input("请输入密码:")
# 检查条件
has_letter = any(c.isalpha() for c in password) # 包含字母
has_digit = any(c.isdigit() for c in password) # 包含数字
has_special = any(not c.isalnum() for c in password) # 包含特殊字符
is_too_short = len(password) < 8 # 太短
is_too_simple = password.isnumeric() or password.isalpha() # 太简单
print(f"\n🔍 密码检查结果:")
print(f" 长度:{len(password)}位")
print(f" 包含字母:{has_letter}")
print(f" 包含数字:{has_digit}")
print(f" 包含特殊字符:{has_special}")
print(f" 太短(<8位):{is_too_short}")
print(f" 太简单(纯数字或纯字母):{is_too_simple}")
print()
# 安全检查
is_secure = (
len(password) >= 8 and
has_letter and
has_digit and
not is_too_simple
)
if is_secure:
print("✅ 密码安全!")
else:
print("❌ 密码不安全!")
print("💡 建议:")
if len(password) < 8:
print(" 📏 密码至少8位")
if not has_letter:
print(" 🔤 至少包含一个字母")
if not has_digit:
print(" 🔢 至少包含一个数字")
if is_too_simple:
print(" 🎯 不要只用数字或字母")
🎪 第六部分:组合逻辑运算
6.1 复杂的组合判断
# 组合逻辑运算
print("🎪 组合逻辑运算")
print("=" * 30)
# 学生情况
math_score = 85
chinese_score = 92
english_score = 78
has_good_attendance = True
completed_project = False
print("📊 学生情况:")
print(f" 数学成绩:{math_score}分")
print(f" 语文成绩:{chinese_score}分")
print(f" 英语成绩:{english_score}分")
print(f" 出勤良好:{has_good_attendance}")
print(f" 完成项目:{completed_project}")
print()
# 复杂的判断条件
# 条件1:所有科目都及格
all_pass = (math_score >= 60) and (chinese_score >= 60) and (english_score >= 60)
# 条件2:至少一科优秀(≥90)
has_excellent = (math_score >= 90) or (chinese_score >= 90) or (english_score >= 90)
# 条件3:平均分优秀
average_score = (math_score + chinese_score + english_score) / 3
is_average_excellent = average_score >= 90
# 条件4:有资格评选三好学生
can_be_model_student = (
all_pass and
has_good_attendance and
(has_excellent or is_average_excellent) and
not completed_project # 还没有完成项目
)
print("🔍 条件分析:")
print(f" 所有科目及格:{all_pass}")
print(f" 至少一科优秀:{has_excellent}")
print(f" 平均分优秀(≥90):{is_average_excellent},平均分:{average_score:.1f}")
print(f" 有资格评选三好学生:{can_be_model_student}")
print()
if can_be_model_student:
print("🎉 恭喜!有资格评选三好学生!")
print("📋 需要:")
print(" ✅ 所有科目及格")
print(" ✅ 出勤良好")
print(" ✅ 至少一科优秀或平均分优秀")
if not completed_project:
print(" 💡 还需要完成项目作业")
else:
print("❌ 暂时没有评选资格")
6.2 实际应用:智能天气建议
# 智能天气建议
print("\n🌤️ 智能天气建议")
print("=" * 30)
# 天气数据
temperature = 28 # 温度
is_raining = False
is_sunny = True
wind_speed = 5 # 风速
is_weekend = True
time_of_day = "下午" # 早上、下午、晚上
print("📅 天气和日期:")
print(f" 温度:{temperature}°C")
print(f" 下雨:{is_raining}")
print(f" 晴天:{is_sunny}")
print(f" 风速:{wind_speed}米/秒")
print(f" 周末:{is_weekend}")
print(f" 时间:{time_of_day}")
print()
# 判断条件
is_hot = temperature > 30
is_cold = temperature < 15
is_windy = wind_speed > 10
is_good_time = time_of_day in ["早上", "下午"]
# 综合建议
print("💡 智能建议:")
# 建议1:是否适合户外活动
suitable_for_outdoor = (
(not is_raining) and
(not is_windy) and
(not is_hot) and
(not is_cold) and
is_good_time
)
if suitable_for_outdoor and is_weekend:
print("✅ 非常适合户外活动!")
if is_sunny:
print(" ☀️ 天气晴朗,可以:")
print(" 🏀 打篮球")
print(" 🚲 骑自行车")
print(" 🌳 公园散步")
else:
print(" ☁️ 天气不错,可以:")
print(" ⚽ 踢足球")
print(" 🎾 打网球")
elif suitable_for_outdoor and not is_weekend:
print("✅ 天气适合户外,但今天是上学日")
print(" 🎒 放学后可以适当活动")
else:
print("❌ 不太适合户外活动")
if is_raining:
print(" ☔ 因为在下雨")
if is_windy:
print(" 💨 因为风太大")
if is_hot:
print(" 🔥 因为天气太热")
if is_cold:
print(" ❄️ 因为天气太冷")
if not is_good_time:
print(" 🌙 因为时间不合适")
# 建议2:穿着建议
print(f"\n👕 穿着建议:")
if is_hot:
print(" 👕 穿短袖,戴帽子")
elif is_cold:
print(" 🧥 穿外套,注意保暖")
else:
print(" 👔 穿长袖,舒适为主")
if is_sunny and not is_raining:
print(" 🧴 记得涂防晒霜")
if is_raining:
print(" ☂️ 记得带伞")
🎮 第七部分:逻辑游戏
游戏1:逻辑推理挑战
# 逻辑推理挑战
print("🔍 逻辑推理挑战")
print("=" * 30)
score = 0
questions = [
{
"question": "小明有作业并且是周末,他能出去玩吗?",
"conditions": ["有作业 = True", "是周末 = True"],
"logic": "有作业 and 是周末",
"answer": False
},
{
"question": "天气好或者有室内场地,能进行体育活动吗?",
"conditions": ["天气好 = True", "有室内场地 = False"],
"logic": "天气好 or 有室内场地",
"answer": True
},
{
"question": "不是周末并且没有作业,能看电视吗?",
"conditions": ["是周末 = False", "有作业 = False"],
"logic": "not 是周末 and not 有作业",
"answer": True
},
{
"question": "数学≥90并且语文≥90,或者是班长,能获奖吗?",
"conditions": ["数学≥90 = True", "语文≥90 = False", "是班长 = True"],
"logic": "(数学≥90 and 语文≥90) or 是班长",
"answer": True
},
{
"question": "天气不好并且不是室内运动,能运动吗?",
"conditions": ["天气好 = False", "是室内运动 = False"],
"logic": "not 天气好 and not 是室内运动",
"answer": False
}
]
print("判断以下情况是否正确(True/False):")
for i, q in enumerate(questions, 1):
print(f"\n{i}. {q['question']}")
print(f" 条件:{', '.join(q['conditions'])}")
print(f" 逻辑:{q['logic']}")
answer = input(" 你的判断(True/False):").strip()
# 处理输入
if answer.lower() in ['true', 't', '是', 'yes', 'y', '1']:
user_answer = True
elif answer.lower() in ['false', 'f', '否', 'no', 'n', '0']:
user_answer = False
else:
print(" ❌ 请输入True或False")
continue
if user_answer == q['answer']:
print(" ✅ 正确!")
score += 1
else:
print(f" ❌ 错误!正确答案是:{q['answer']}")
print(f"\n📊 得分:{score}/{len(questions)}")
if score == len(questions):
print("🎉 逻辑推理大师!")
elif score >= 3:
print("👍 很棒!逻辑思维不错!")
else:
print("💪 加油!多做练习会更好!")
游戏2:密室逃脱逻辑谜题
# 密室逃脱逻辑谜题
print("🚪 密室逃脱逻辑谜题")
print("=" * 30)
print("你被困在一个密室里,需要找到正确的开门方法!")
print("房间里有4个开关:A、B、C、D")
print("每个开关可以是打开(True)或关闭(False)")
print()
# 生成谜题
import random
# 随机设置正确答案
A = random.choice([True, False])
B = random.choice([True, False])
C = random.choice([True, False])
D = random.choice([True, False])
# 开门条件
door_condition = (
(A and not B) or
(C and D) or
(not A and B and not C)
)
print("🔍 线索:")
print("1. 如果A开并且B关,门能开")
print("2. 如果C和D都开,门能开")
print("3. 如果A关、B开、C关,门能开")
print()
print("💡 提示:使用 or 连接不同的开门条件")
print()
# 用户尝试
attempts = 3
for attempt in range(1, attempts + 1):
print(f"尝试 {attempt}/{attempts}")
# 获取用户选择
try:
a_input = input("开关A(开/关):").strip()
b_input = input("开关B(开/关):").strip()
c_input = input("开关C(开/关):").strip()
d_input = input("开关D(开/关):").strip()
# 转换为布尔值
user_A = a_input.lower() in ['开', 'true', 't', '是', 'yes', 'y', '1']
user_B = b_input.lower() in ['开', 'true', 't', '是', 'yes', 'y', '1']
user_C = c_input.lower() in ['开', 'true', 't', '是', 'yes', 'y', '1']
user_D = d_input.lower() in ['开', 'true', 't', '是', 'yes', 'y', '1']
# 检查是否能开门
user_condition = (
(user_A and not user_B) or
(user_C and user_D) or
(not user_A and user_B and not user_C)
)
if user_condition:
print("🎉 恭喜!门开了!你逃出去了!")
break
else:
print("❌ 门没有开,再试试!")
if attempt < attempts:
print("💡 提示:")
if (user_A and not user_B) != (A and not B):
print(" A和B的组合不对")
if (user_C and user_D) != (C and D):
print(" C和D的组合不对")
if (not user_A and user_B and not user_C) != (not A and B and not C):
print(" A、B、C的组合不对")
print()
except:
print("❌ 输入错误,请重新尝试!")
print()
if attempt == attempts and not user_condition:
print(f"💀 尝试次数用尽!正确答案是:")
print(f" A={A}, B={B}, C={C}, D={D}")
📅 下节课预告
第15课:格式化输出魔法——f-string格式化
下节课你将学习:
- 使用f-string进行漂亮的格式化输出
- 控制数字的小数位数
- 对齐和填充文本
- 制作美观的表格和报告
- 综合应用格式化技巧
预习思考:
- 如何让数字只显示两位小数?
- 如何让文字对齐显示?
- 如何在字符串中插入变量值?
💬 给家长的话
亲爱的家长:
今天孩子学习了逻辑运算符,这是编程中非常重要的概念,能让孩子写出更智能、更有逻辑的程序。
孩子今天学会了:
- ✅ 逻辑运算符
and、or、not的用法 - ✅ 理解逻辑运算的真值表
- ✅ 组合多个条件进行复杂判断
- ✅ 在实际问题中应用逻辑运算
- ✅ 解决逻辑推理问题
逻辑思维的重要性:
| 逻辑运算 | 生活示例 | 编程意义 | 思维培养 |
|---------|---------|---------|---------|
| and | 既要...又要... | 同时满足多个条件 | 综合思维 |
| or | 或者...或者... | 满足一个条件 | 选择思维 |
| not | 不是... | 取反判断 | 逆向思维 |
| 组合 | 复杂条件判断 | 智能决策 | 逻辑思维 |
您可以这样做:
生活应用:
- 日常决策:用逻辑运算描述日常决策
- 游戏规则:设计需要逻辑判断的小游戏
- 学习计划:制定需要多个条件的学习计划
- 安全规则:讨论网络安全中的逻辑判断
思维训练:
- 讨论:生活中的"并且"、"或者"、"不"
- 思考:如何组合多个条件做决策
- 设计:创建自己的逻辑谜题
- 实践:用逻辑运算解决实际问题
温馨提示:
- 逻辑思维是编程的核心能力
- 通过游戏让逻辑学习更有趣
- 鼓励孩子在生活中应用逻辑思维
- 多练习真值表,加深理解
🏆 今日成就
完成了今天的学习,你:
🔍 掌握了逻辑运算符
📊 理解了真值表
🎯 学会了组合判断
🎮 完成了逻辑游戏
💡 提升了逻辑思维
挑战任务:
- 设计一个智能决策程序
- 创建一个逻辑推理游戏
- 制作个人学习计划检查器
- 编写密码安全强度检查器
🌟 编程心法
逻辑是程序的大脑
and 是严格的要求
or 是灵活的选择
not 是相反的视角
组合逻辑运算
让程序更聪明
从简单判断到复杂决策
逻辑是你的导航
掌握逻辑之道
让程序拥有智慧
记住:良好的逻辑思维能力,让你能写出更智能、更健壮的程序。这是成为优秀程序员的必备技能!
第14课结束。你现在已经是逻辑小侦探了!
实践任务:
1. 设计智能天气建议程序
2. 创建密码安全检查工具
3. 制作学习计划评估系统
4. 编写逻辑推理游戏
下节课,让我们学习格式化输出,让程序输出更美观!
第15课见!✨