总体来说,条件控制的效果类似c/c++/c#/java中的,只不过在语法格式的层面上存在一定的差异。
1. if条件语法格式
if condition_1:
...
elif condition_2:
...
else:
...
1、python 中用 elif 代替了 c/c++中的 else if,所以if语句的关键字为:if – elif – else。
2、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
3、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
4、在 python 中没有 switch...case 语句,但在 python3.10中添加了 match...case,功能类似。
5、if操作中常用的运算符:<、<=、>、>=、==、!=。
# 示例代码
number = input('Please input a number:> ')
if(int(number) % 2 == 0):
print("输入的是偶数.")
else:
print("输入的是奇数.")

2. if的嵌套
类似c/c++中的if嵌套,可以对if分支结构进行嵌套。
# 以下案例是示例型案例, 可能实际意义, 只是为了讲解if的嵌套效果。
number = int(input('Please input a number:> '))
if(number < 5):
print('输入的数字小于5.')
if(number % 2 == 0):
print("输入的是偶数.")
else:
print("输入的是奇数.")
elif(number < 10):
print('输入的数字大于5且小于10.')
else:
print('输入的数字大于10.')

3. match…case
python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。
match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式;否则直接跳过,_ 可以匹配一切。
match...case实际上类似于c/c++中的switch...case。
(1) 语法格式:
case _: 类似于 c/c++/java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。
match subject:
case pattern_1:
...
case pattern_2:
...
case pattern_3:
...
case _:
...
# 因为本篇是基于python3.9讲解的, 所以此处无法在PyCharm中演示match...case;
# 为此我切换到虚拟机当中, 安装python3.10, 并使用python自带的IDLE进行编写运行;
def getStatus(value):
match value:
case -1:
return "fail."
case 1:
return "success."
case 0:
return "unknow."
case _:
return "other."
print(getStatus(1))

实际上,此处只是简单的提及了一下match…case…的最基本用法, 下一篇我们将深入讲解match…case…的用法。。。
敬请期待。。。


















