流程控制

流程:代码执行的过程

控制:对代码执行过程的把控

三大结构

顺序结构:代码默认从上到下,依次执行

分支结构:单项分支,双向分支,多项分支,巢状分支

循环结构:while循环和for循环

单项分支

语句:

if 条件表达式:

code1

code2

当条件表达式成立时,返回True,执行对应的代码块

job = "programmer"
if job == "programmer":
print("钱多")
print("话少")
print("*的早")

双向分支(二选一)

语句:

if 条件表达式:

code1 ..

else:

code2 ...

如果条件表达式成立,返回True ,执行if这个区间的代码块

如果条件表达式不成立,返回False,执行else这个区间的代码块

job = "programmer"
if job == "programmer":
print("钱多")
print("话少")
print("*的早")
else:
print("给你小红花儿~")

多项分支(多选一)

语句:

if 条件表达式1:

code1

elif 条件表达式2:

code2

elif 条件表达式3:

code3

else:

code4

如果条件表达式1成立,执行对应分支的代码块code1,反之则判断条件表达式2是否成立

如果条件表达式2成立,执行对应分支的代码块code2,反之则判断条件表达式3是否成立

如果条件表达式3成立,执行对应分支的代码块code3,反之则执行else分支,到此程序执行完毕

money = False
car = False
house = False
if money == True:
print("你是土豪么???")
elif car == True:
print("你是有一辆蹦蹦嘛???")
elif house == True:
print("你是什么房子啊?")
else:
print("你是个好人~")

巢状分支

单项分支,双向分支,多项分支的互相嵌套组合

money = False
car = True
house = True
if money == True:
print("你是土豪么???")
if house == True:
print("你是什么房子啊?")
if car == True:
print("你是有一辆蹦蹦嘛???")
else:
print("其实还可以~")
else:
print("感觉差点意思~")
else:
print("你是个好人~")

循环结构

特点:

减少冗余代码,提升代码执行效率

语法:

while 条件表达式:

code1

书写三部曲

初始化一个变量

书写循环条件

添加自增/自减的值

案例1

# 打印1~100所有数字
i = 1
while i <= 100:
print(i)
i += 1

案例2

# 打印1~100的累加和
i = 0
total = 0
while i <= 100:
total += i
i += 1
print(total)

死循环

while True:

print("死循环")

关键字的使用

pass(代码块中的占位符)
while True:
pass
break(终止当前循环)
# 1~10,遇到5终止循环
i = 1
while i <= 10:
print(i)
if i == 5:
break
i += 1
container(跳过当前循环)
# 打印1~100中不含4的数字
i = 1
while i <= 100:
strvar = str(i)
if "4" in strvar:
i += 1
continue
print(i)
i += 1

for循环

循环/遍历/迭代,把容器中的元素一个个取出来

while的局限性

# Error
# setvar = {"a", "b", "c"}
# i = 0
# while i < len(setvar):
# print(setvar[i])
# i+=1

for循环的基本语法

for 变量 in Iterable:

code1

Iterable

Iterable可迭代性数据

容器类型数据

range对象

迭代器

range

range(开始值,结束值,步长)

区间为[开始值,结束值),为左闭右开区间,右边的结束值取不到

总结

while:一般用于处理复杂的逻辑关系

for:一般用于迭代数据

部分情况下两个循环可以互相转换

以上就是详解Python流程控制语句的详细内容