Python3(12) 条件控制
在 Python 编程的世界里,条件控制语句是构建逻辑的关键工具。它能让程序根据不同的条件执行不同的代码块,实现多样化的功能。这篇博客将结合菜鸟教程的内容,通过代码示例深入学习 Python3 的条件控制,方便日后复习回顾。
一、if 语句基础
1.1 if 语句的基本结构
Python 中 if 语句的基本形式为:
if condition:statement_block
其中,condition
是一个表达式,其结果为True
或False
。当condition
为True
时,会执行缩进的statement_block
代码块。例如:
num = 10
if num > 5:print(f"{num}大于5")
运行这段代码,因为num > 5
的结果为True
,所以会输出10大于5
。
1.2 if - elif - else 结构
if 语句可以结合elif
(相当于其他语言中的else if
)和else
使用,形成更复杂的条件判断结构。其形式如下:
if condition_1:statement_block_1
elif condition_2:statement_block_2
else:statement_block_3
程序会依次判断condition_1
、condition_2
等条件,当某个条件为True
时,执行对应的代码块,后续条件将不再判断。若所有条件都为False
,则执行else
后的代码块。比如:
score = 85
if score >= 90:print("成绩优秀")
elif score >= 80:print("成绩良好")
else:print("成绩有待提高")
这里score
为 85,满足score >= 80
,所以输出成绩良好
。
1.3 条件判断中的操作符
在条件判断中,常用的操作符有<
(小于)、<=
(小于或等于)、>
(大于)、>=
(大于或等于)、==
(等于)、!=
(不等于)。例如:
a = 5
b = 10
print(a < b)
print(a == b)
别输出True
和False
,展示了小于和等于操作符的使用。
二、if 语句的应用实例
2.1 简单的条件判断
下面的代码根据输入的数字判断其正负性:
num = int(input("请输入一个数字: "))
if num > 0:print(f"{num}是正数")
elif num < 0:print(f"{num}是负数")
else:print(f"{num}是零")
运行程序后,输入不同的数字,程序会根据条件输出相应的结果。
2.2 数字猜谜游戏
这是一个经典的数字猜谜游戏示例:
import randomnumber = random.randint(1, 100)
guess = -1
print("数字猜谜游戏!")
while guess != number:guess = int(input("请输入你猜的数字:"))if guess == number:print("恭喜,你猜对了!")elif guess < number:print("猜的数字小了...")elif guess > number:print("猜的数字大了...")
程序会随机生成一个 1 到 100 之间的数字,玩家通过输入猜测数字,根据提示不断调整,直到猜对为止。
三、if 嵌套
3.1 if 嵌套的结构
if 嵌套就是在一个 if 语句的代码块中再包含另一个 if 语句,结构如下:
if outer_condition:if inner_condition:inner_statement_blockelse:other_inner_statement_block
else:outer_else_statement_block
例如,判断一个数字是否同时满足能被 2 整除且能被 3 整除:
num = int(input("输入一个数字:"))
if num % 2 == 0:if num % 3 == 0:print(f"{num}可以同时被2和3整除")else:print(f"{num}可以被2整除,但不能被3整除")
else:if num % 3 == 0:print(f"{num}可以被3整除,但不能被2整除")else:print(f"{num}既不能被2整除,也不能被3整除")
通过输入不同的数字,程序会进行相应的判断和输出。
四、Python 3.10 的 match...case 语句
4.1 match...case 的基本用法
Python 3.10 引入的match...case
语句为条件判断提供了新的方式。它的基本语法如下:
match subject:case <pattern_1>:<action_1>case <pattern_2>:<action_2>case <pattern_3>:<action_3>case _:<action_wildcard>
match
后的subject
会依次与case
后的模式进行匹配,匹配成功则执行相应的代码块。例如:
def http_error(status):match status:case 400:return "Bad request"case 404:return "Not found"case 418:return "I'm a teapot"case _:return "Something's wrong with the internet"mystatus = 400
print(http_error(400))
这里status
为 400,匹配到case 400
,所以输出Bad request
。
4.2 多条件匹配
一个case
可以设置多个匹配条件,用|
隔开。例如:
def permission_check(status):match status:case 401 | 403 | 404:return "Not allowed"case _:return "Allowed"print(permission_check(403))
status
为 403 时,满足401 | 403 | 404
的条件,输出Not allowed
。
五、总结
Python3 的条件控制语句(if 语句和 match...case 语句)是编程中实现逻辑控制的重要手段。通过灵活运用这些语句,结合各种条件操作符,能让程序根据不同的情况执行不同的代码,实现多样化的功能。在实际编程中,要根据具体需求选择合适的条件控制结构,合理嵌套,以优化代码逻辑和提高程序的可读性。希望这篇博客能帮助你更好地复习和巩固 Python3 条件控制的知识,在编程实践中灵活运用。