Python 程序控制结构

Python 程序控制结构

第一部分 条件测试

1. 比较运算

>
<
>=
<=
==
!=
a=1
b=2
a>b
False

非空

ls = []
if ls:
    print("非空")
else:
    print("空的")
空的

2. 逻辑运算

  • 与或非
and #一个假全假
or #一个真全真
not
  • 优先级 非>与>或
print(True or False and False)
True

3. 存在运算

  • 元素 in 列表/字符串
  • 元素 not in 列表/字符串
rng = ["uzi","ming","mlxg"]
print("uzi" in rng)
True

第二部分 分支结构——if 语句

1. 单分支

  • 模板
    if 条件:

    缩进的代码块

age = 20
if age >= 18:
    print("成年")
成年

2. 二分支

  • 模板
    if 条件:
    缩进代码块
    else:
    缩进代码块
age = 18
if age >= 18:
    print("成年")
else:
    print("未成年")
成年

3. 多分支

  • 模板
    if 条件:
    缩进的代码块
    elif 条件:
    缩进的代码块

    else 条件:
    缩进的代码块
age = 1
if age >= 18:
    print("成年")
elif age > 22:
    print("结婚")
else:
    print("未成年")
未成年

4. 嵌套语句

age = eval(input("输入你的年龄: "))
if age > 22:
    friends = bool(eval(input("有对象输1,没对象输0: ")))
    if friends:
        print("可以结婚")
    else:
        print("不可以结婚")
else:
    print("不可以结婚")
输入你的年龄: 24
有对象输1,没对象输0: 1
可以结婚

第三部分 遍历循环——for循环

主要形式

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

执行过程:

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

1. 直接迭代——列表[]、元组()、集合{}、字符串""

rng = ("uzi","ming","mlxg")
for LPL in rng:
    print("LPL,"+LPL)
LPL,uzi
LPL,ming
LPL,mlxg

2. 变换迭代——字典

rng = {101:'uzi',202:'ming',303:'mlxg'}
for k,v in rng.items():
    print(k,v)
101 uzi
202 ming
303 mlxg

3. range()对象

res=[]
for i in range(10000):
    res.append(i**2)
print(res[:1])
print(res[-1])
[0]
99980001

循环控制: break 和 continue

  • break 结束整个循环
product_scores = [89,90,23,45,87,97,67] #评分小于90的超过一个则不合格
i = 0
for score in product_scores:
    if score<90:
        i+=1
    if i==2:
        print("不合格")
        break
不合格
  • continue 结束本次循环
product_scores = [89,90,23,45,87,97,67] #评分小于90的超过一个则不合格
print(len(product_scores))
for i in range(len(product_scores)):
    if product_scores[i]>=90:
        continue
    print("第{}个产品,分数为{},不合格".format(i,product_scores[i]))
7
第0个产品,分数为89,不合格
第2个产品,分数为23,不合格
第3个产品,分数为45,不合格
第4个产品,分数为87,不合格
第6个产品,分数为67,不合格

第四部分 无限循环——while循环

4.1 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("猜对啦")
>>:18
猜对啦

4.2 风向标

albert_age=18
flag = True
guess = int(input(">>:"))
while flag:
    if guess > albert_age:
        print("太大啦")
    elif guess < albert_age:
        print("太小啦")
    else:
        print("猜对啦")
    flag = False
>>:18
猜对啦

4.3 while 循环与 break Continue

albert_age=18
guess = int(input(">>:"))
while True:
    if guess > albert_age:
        print("太大啦")
    elif guess < albert_age:
        print("太小啦")
    else:
        print("猜对啦")
    break
>>:18
猜对啦
i = 0
while i<10:
    i+=1
    if i%2 ==0:
        continue
    print(i)
1
3
5
7
9

第五部分 控制语句需要注意的问题

5.1 尽可能减少嵌套

5.2 避免死循环

5.3 判断式不要过于复杂——可以封装为函数


发布了33 篇原创文章 · 获赞 2 · 访问量 943

猜你喜欢

转载自blog.csdn.net/Btbsja/article/details/104571270