【Python】DS的基础学习笔记4:程序控制结构

程序控制结构

非顺序式的程序控制,往往需要根据一定的条件,决定程序运行的路线。因此,我们首先来认识一下什么叫条件测试。

4.1 条件测试

4.1.1 比较运算

a = 10
b = 8
print(a > b)  # 大于
print(a < b)  # 小于
print(a >= b)  # 大于等于
print(a <= b)  # 小于等于
print(a == b)  # 等于
print(a != b)  # 不等于

True
False
True
False
False
True

  • 非空
ls = []
if ls:
    print("非空")  # 数据结构不为空,变量不为0、None、False则条件成立
else:
    print("空的")

空的

4.1.2 逻辑运算

  • 与、或、非
a = 10
b = 8
c = 12
print((a > b) and (b > c))  # 与
print((a > b) or (b > c))  # 或
print(not(a > b))  # 非

False
True
False

  • 复合逻辑运算的优先级

    非>与>或

print(True or True and False)
print((True or True) and False)

True
False

4.1.3 存在运算

元素 in 列表/字符串
元素 not in 列表/字符串

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print("BMW" in cars)
print("BENZ" in cars)
print("BMW" not in cars)
print("BENZ" not in cars)

True
False
False
True

4.2 分支结构——if语句

4.1.1 单分支

模板

if 条件:
  缩进的代码块

age = 8
if age > 7:
    print("孩子,你该上学啦!")

孩子,你该上学啦!

4.1.2 二分支

模板

if 条件:
  缩进的代码块
else:
  缩进的代码块

age = 6
if age > 7:
    print("孩子,你该上学啦!")
else:
    print("再玩两年泥巴!")

再玩两年泥巴!

4.1.3 多分支

模板

if 条件:
  缩进的代码块
elif 条件:
  缩进的代码块
elif 条件:
  缩进的代码块

else:
  缩进的代码块

age = 38
if age < 7:
    print("再玩两年泥巴!")
elif age < 13:
    print("孩子,你该上小学啦")
elif age < 16:
    print("孩子,你该上初中啦")
elif age < 19:
    print("孩子,你该上高中啦")
elif age < 23:
    print("大学生活快乐")
elif age < 60:
    print("辛苦了,各行各业的工作者们")
else:  # 有时为了清楚,也可以写成elif age >= 60:
    print("享受退休生活吧")

辛苦了,各行各业的工作者们

不管多少分支,最后只执行一个分支

4.1.4 嵌套语句

题目:年满18周岁,在非公共场合方可抽烟,判断某种情形下是否可以抽烟

age = eval(input("请输入年龄"))
if age > 18:
    is_public_place = bool(eval(input("公共场合输入1,非公共场合输入0")))
    if not is_public_place:
        print("可以抽烟")
    else:
        print("禁止抽烟")
else:
    print("禁止抽烟")

请输入年龄20
公共场合输入1,非公共场合输入00
可以抽烟

4.3 遍历循环——for循环

主要形式:

  • for 元素 in 可迭代对象:
       执行语句

执行过程:

  • 从可迭代对象中,依次取出每一个元素,并进行相应的操作

4.3.1 直接迭代

用于可迭代对象为列表[]、元组()、集合{}、字符串""

graduates = ("李雷", "韩梅梅", "Jim")
for graduate in graduates:
    print("Congratulations,"+graduate)

Congratulations,李雷
Congratulations,韩梅梅
Congratulations,Jim

4.3.2 变换迭代

适用于可迭代对象为字典类型

students = {201901: "小明", 201902: "小红", 201903: "小强"}
for k, v in students.items():
    print(k, v)
for student in students:
    print(student)

201901 小明
201902 小红
201903 小强
201901
201902
201903

4.3.3 range()对象

res = []
for i in range(10000):
    res.append(i**2)
print(res[:5])

[0, 1, 4, 9, 16]

res = []
for i in range(1, 10, 2):
    res.append(i**2)
print(res)

[1, 9, 25, 49, 81]

4.3.4 循环控制:break和continue

  • break结束整个循环
product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82]  # 1组10个产品的性能评分
# 如果低于75分的超过2个,则该组产品不合格
i = 0
for score in product_scores:
    if score < 75:
        i += 1
    if i == 2:
        print("产品抽验不合格")
        break

产品抽验不合格

  • continue 结束本次循环
product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82]  # 1组10个产品的性能评分
# 如果低于75分,输出警示
print(len(product_scores))
for i in range(len(product_scores)):
    if product_scores[i] > 75:
        continue
    print("第{0}个产品,分数为{1},不合格".format(i+1, product_scores[i]))

10
第4个产品,分数为70,不合格
第5个产品,分数为67,不合格

4.3.5 for与else的配合

如果for循环全部执行完毕,没有被break中止,则运行else块

product_scores = [89, 90, 99, 70, 79, 78, 85, 92, 77, 82]  # 1组10个产品的性能评分
# 如果低于75分的超过2个,则该组产品不合格
i = 0
for score in product_scores:
    if score < 75:
        i += 1
    if i == 2:
        print("产品检验不合格")
        break
else:
    print("产品检验合格")

产品检验合格

4.4 无限循环——while循环

4.4.1 为什么要用while循环

  • 经典题目:猜数字
albert_age = 18
# 第1次
guess = int(input(">>:"))
if guess > albert_age:
    print("猜的太大了,往小里试试…")
elif guess < albert_age:
    print("猜的太小了,往大里试试…")
else:
    print("恭喜你,猜对了…")
# 第2次
guess = int(input(">>:"))
if guess > albert_age:
    print("猜的太大了,往小里试试…")
elif guess < albert_age:
    print("猜的太小了,往大里试试…")
else:
    print("恭喜你,猜对了…")

代码可能需要重复执行,可是又不知道具体要执行多少次
因此我们需要while循环

4.4.2 while循环的一般形式

主要形式

  • while 判断条件:
      执行语句

  • 条件为真,执行语句
    条件为假,while循环结束

albert_age = 18
guess = int(input(">>:"))
while guess != albert_age:
    if guess > albert_age:
        print("猜的太大了,往小里试试…")
    elif guess < albert_age:
        print("猜的太小了,往大里试试…")
    guess = int(input(">>:"))
print("恭喜你,猜对了…")

>>:3
猜的太小了,往大里试试…
>>:18
恭喜你,猜对了…

4.4.3 while与风向标

albert_age = 18
flag = True  # 布尔类型
while flag:
    guess = int(input(">>:"))
    if guess > albert_age:
        print("猜的太大了,往小里试试…")
    elif guess < albert_age:
        print("猜的太小了,往大里试试…")
    else:
        print("恭喜你,猜对了…")
        flag = False  # 当诉求得到满足,就让风向变一下
flag = True
while flag:
    pass
    while flag:
        pass
        while flag:
            flag = False  # 循环逐层判断,当flag为False时,循环会逐层退出

4.4.4 while与循环控制break、continue

albert_age = 18
while True:
    guess = int(input(">>:"))
    if guess > albert_age:
        print("猜的太大了,往小里试试…")
    elif guess < albert_age:
        print("猜的太小了,往大里试试…")
    else:
        print("恭喜你,猜对了…")
        break  # 当诉求得到满足,就跳出循环

输出10以内的奇数

i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue  # 跳出本次循环,进入下一次循环 
    print(i)

1
3
5
7
9

4.4.5 while与else

如果while循环全部执行完毕,没有被break中止,则运行else块

count = 0
while count <= 5:
    count += 1
    print("Loop", count)
else:
    print("循环正常执行")

Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行

4.4.6 再看两个例子

【小例子】删除列表中的特定值

pets = ["dog", "cat", "dog", "pig", "goldfish", "rabbit", "cat"]
while "cat" in pets:
    pets.remove("cat")
print(pets)

[‘dog’, ‘dog’, ‘pig’, ‘goldfish’, ‘rabbit’]

【小例子】将未读书籍列表中的书名分别输出后,存入已读书籍列表

not_read = ["红楼梦", "水浒传", "三国演义", "西游记"]
have_read = []
while not_read:
    book = not_read.pop()
    have_read.append(book)
    print("我已经读过《{}》了".format(book))
print(not_read)
print(have_read)

我已经读过《西游记》了
我已经读过《三国演义》了
我已经读过《水浒传》了
我已经读过《红楼梦》了
[]
[‘西游记’, ‘三国演义’, ‘水浒传’, ‘红楼梦’]

4.5 控制语句注意问题

4.5.1 尽可能减少多层嵌套

  • 可读性差,容易把人搞疯掉
if 条件:
    执行语句
    if 条件:
        执行语句
        if

4.5.2 避免死循环

条件一直成立,循环永无止境

while True:
    print("我就这样一直不停下来")

4.5.3 避免封装过于复杂的判断条件

如果条件判断里的表达式过于复杂
出现了太多的 not/and/or 等
导致可读性大打折扣
考虑将条件封装为函数

a, b, c, d, e = 10, 8, 6, 2, 0
if (a > b) and (c > d) and (not e):
    print("我已经晕了")

我已经晕了

numbers = [10, 8, 6, 2, 0]


def judge(num):
    a, b, c, d, e = num
    x = a > b
    y = c > d
    z = not e
    return x and y and z


if judge(numbers):
    print("不会晕了欸")

不会晕了欸

以上,便是第四节深入探索内容,包含条件测试、if、for、while等内容。
下一节将深入理解函数,面向过程的编程。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值