第11集:if条件语句基础
本集学习目标
- 理解条件语句的概念和作用
- 掌握if语句的基本语法
- 学会使用关系运算符和逻辑运算符构建条件
- 理解缩进在Python中的重要性
- 通过实际练习掌握条件语句的使用
什么是条件语句?
条件语句是编程中最重要的控制结构之一,它允许程序根据不同的条件执行不同的代码。简单来说,条件语句就是让程序"做判断"。
生活中的类比:
- 如果下雨,就带伞
- 如果考试及格,就去玩;如果不及格,就复习
- 如果年龄大于18岁,就可以投票
在Python中,我们使用if语句来实现这种条件判断。
if语句的基本语法
if 条件:
# 条件为True时执行的代码块
执行语句1
执行语句2
...语法要点:
if是Python关键字,必须小写条件后必须有冒号:- 条件为True时,执行的代码必须缩进(通常是4个空格)
- 缩进的代码块称为
if的"主体"或"子句"
示例1:简单的if语句
age = 20
if age >= 18:
print("你已经成年了!")
print("你可以投票了!")
print("程序结束")执行结果:
你已经成年了!
你可以投票了!
程序结束解释:
age >= 18条件为True,所以执行缩进的代码块print("程序结束")不在if语句块内,所以总是会执行
示例2:条件为False的情况
age = 15
if age >= 18:
print("你已经成年了!")
print("你可以投票了!")
print("程序结束")执行结果:
程序结束解释:
age >= 18条件为False,跳过if代码块- 直接执行后面的非缩进语句
条件表达式
条件可以是任何可以求值为True或False的表达式。
关系运算符
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
== |
等于 | 5 == 5 |
True |
!= |
不等于 | 5 != 3 |
True |
> |
大于 | 5 > 3 |
True |
< |
小于 | 3 < 5 |
True |
>= |
大于等于 | 5 >= 5 |
True |
<= |
小于等于 | 3 <= 5 |
True |
逻辑运算符
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
and |
逻辑与(两个都为True才为True) | True and True |
True |
or |
逻辑或(有一个为True就为True) | True or False |
True |
not |
逻辑非(取反) | not True |
False |
成员运算符
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
in |
在...中 | 'a' in 'apple' |
True |
not in |
不在...中 | 'z' not in 'apple' |
True |
身份运算符
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
is |
是同一个对象 | x is y |
True/False |
is not |
不是同一个对象 | x is not y |
True/False |
详细示例讲解
示例3:使用关系运算符
# 判断数字是否为正数
number = -5
if number > 0:
print(f"{number} 是正数")
if number < 0:
print(f"{number} 是负数")
if number == 0:
print(f"{number} 是零")输出:
-5 是负数示例4:使用逻辑运算符
# 判断成绩是否优秀
score = 95
if score >= 90:
print("优秀!")
print("你的成绩非常棒!")
# 判断是否及格
if score >= 60:
print("恭喜你,及格了!")输出:
优秀!
你的成绩非常棒!
恭喜你,及格了!示例5:复合条件(使用and)
age = 25
has_license = True
# 只有同时满足两个条件才能开车
if age >= 18 and has_license:
print("你可以开车了!")
if not (age >= 18 and has_license):
print("你还不能开车!")输出:
你可以开车了!示例6:使用or
day = "Saturday"
# 判断是否是周末
if day == "Saturday" or day == "Sunday":
print("今天是周末,好好休息!")输出:
今天是周末,好好休息!示例7:使用in
fruits = ["apple", "banana", "orange"]
fruit = "apple"
if fruit in fruits:
print(f"是的,我们有 {fruit}")
fruit = "grape"
if fruit not in fruits:
print(f"抱歉,我们没有 {fruit}")输出:
是的,我们有 apple
抱歉,我们没有 grapePython的缩进规则
Python使用缩进来表示代码块,这是Python的显著特点。
缩进的规则
- 使用一致的缩进(推荐4个空格)
- 同一个代码块内的缩进级别必须相同
- 不能混用Tab和空格
示例8:正确的缩进
score = 85
if score >= 90:
print("优秀") # 4个空格缩进
print("继续努力!") # 4个空格缩进
print("程序结束") # 不缩进,不在if块内示例9:错误的缩进
score = 85
if score >= 90:
print("优秀") # 4个空格
print("继续努力!") # 错误:缩进不一致
print("程序结束")错误:IndentationError: unexpected indent
条件表达式详解
示例10:数值作为条件
在Python中,任何值都可以被当作布尔值判断。
# 数值:0为False,非0为True
if 5:
print("5是真值")
if 0:
print("0是真值") # 这行不会执行
if -1:
print("-1是真值")输出:
5是真值
-1是真值示例11:字符串作为条件
# 字符串:空字符串为False,非空为True
if "hello":
print("'hello'是真值")
if "":
print("''是真值") # 这行不会执行
if " ":
print("' '(空格)是真值")输出:
'hello'是真值
' '(空格)是真值示例12:列表/元组/字典作为条件
# 容器:空容器为False,非空为True
if [1, 2, 3]:
print("[1, 2, 3]是真值")
if []:
print("[]是真值") # 这行不会执行
if {"name": "张三"}:
print("{'name': '张三'}是真值")
if {}:
print("{}是真值") # 这行不会执行输出:
[1, 2, 3]是真值
{'name': '张三'}是真值常见应用场景
场景1:用户权限检查
user_role = "admin"
if user_role == "admin":
print("你有管理员权限")
print("可以访问所有功能")场景2:登录验证
username = "admin"
password = "123456"
correct_username = "admin"
correct_password = "123456"
if username == correct_username and password == correct_password:
print("登录成功!")
print("欢迎回来," + username)场景3:年龄判断
age = 12
if age < 6:
print("你还太小,不能上学")
if age >= 6 and age < 12:
print("你是小学生")
if age >= 12 and age < 18:
print("你是中学生")
if age >= 18:
print("你已经成年了")场景4:成绩评级
score = 85
if score >= 90:
grade = 'A'
if score >= 80 and score < 90:
grade = 'B'
if score >= 70 and score < 80:
grade = 'C'
if score >= 60 and score < 70:
grade = 'D'
if score < 60:
grade = 'F'
print(f"你的成绩等级是:{grade}")常见错误与注意事项
错误1:忘记冒号
# 错误
age = 20
if age >= 18 # 忘记冒号
print("成年人")正确:
age = 20
if age >= 18: # 加上冒号
print("成年人")错误2:缩进不正确
# 错误:缩进不一致
if age >= 18:
print("成年人")
print("可以投票") # 错误:缩进不一致正确:
if age >= 18:
print("成年人")
print("可以投票") # 正确:缩进一致错误3:赋值与比较混淆
# 错误:使用了赋值运算符 =
age = 18
if age = 18: # 错误:应该是 ==
print("成年人")正确:
age = 18
if age == 18: # 正确:使用比较运算符 ==
print("成年人")错误4:逻辑运算符使用不当
# 错误:不能直接使用数学运算符
if 5 < age < 18:
print("青少年")Python中这种写法是正确的(链式比较),但在其他语言中应该写成:
if age > 5 and age < 18:
print("青少年")本集小结
- if语句是Python中最基本的条件语句,用于根据条件执行代码
- 条件表达式必须求值为True或False
- 关系运算符:
==,!=,>,<,>=,<= - 逻辑运算符:
and,or,not - 缩进在Python中非常重要,用于表示代码块
- 任何值都可以作为条件,0、空字符串、空容器等被视为False
- 冒号
:是if语句不可缺少的部分 - 链式比较:Python支持
a < b < c这种写法
课后练习
练习1:基本if语句
编写程序,判断一个数字是否为偶数。
number = 10
# 你的代码在这里练习2:逻辑运算符
编写程序,判断一个人是否符合驾照申请条件:
- 年龄必须大于等于18
- 必须有身份证
age = 20
has_id_card = True
# 你的代码在这里练习3:成绩判断
编写程序,判断成绩是否及格、良好或优秀:
- 及格:>= 60
- 良好:>= 80
- 优秀:>= 90
score = 85
# 你的代码在这里练习4:用户登录
编写程序,验证用户名和密码:
- 用户名:admin
- 密码:123456
username = input("请输入用户名:")
password = input("请输入密码:")
# 你的代码在这里练习5:闰年判断
编写程序,判断一个年份是否为闰年:
- 能被4整除但不能被100整除,或者能被400整除
year = 2024
# 你的代码在这里下集预告
下一集我们将学习第12集:if-else条件语句。使用if-else语句,我们可以让程序在条件为False时也执行特定的代码,实现更完整的条件判断逻辑。
敬请期待!