02_更多控制流工具

控制语句

if & elif & else 语句

x = int(input("请输入一个整数:"))
if x > 0:
  print('x > 0')
elif x == 0:
  print('Single')
elif x < 0:
  print('x < 0')更多

在python中 elif是else if 的缩写

for 语句

语法: for [name] in [list_name]

word = ['dog', 'cat', 'pig']
for i in word:
  print(i, len(i))

02_for语句.py
dog 3
cat 3
pig 3

​ i为列表的元素,每输出一次,自身+1,不需要像Java手动for(int i = 0; [条件]; i++), 不能像Java,能够自定义循环区间,循环一次直接遍历整个列表

# 创建示例多项集
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# 策略:迭代一个副本
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# 策略:创建一个新多项集
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

​ 迭代:

​ users.copy().items()

range()函数

range([a], b, [c]): 用于生成等差数列,公差为c。 生成列表的范围:a到b-1,a可选填(默认为0)c可选填(默认为1)

for i in range(0, 5):
  print(i)

py/03_range()函数.py"
0
1
2
3
4

range()只有在被迭代的时候才会生成所期望的值,它本身并不返回一个实际的列表

>>> range(5)
range(0, 5)		#直接打印range()并不会返回一个实际的列表

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

break & continue

break:跳出最近一层的for 或者 while循环

continue:继续执行下一次迭代

continue

for i in range(5):
  if i % 2 == 0:    #当i为偶数时输出
    print(f"found a even num {i}")
    continue  #输出完成后,直接执行下一此迭代 不再执行下方的代码
  print(f'found a odd num {i}')

break

for i in range(5):
  for j in range(5):
    if i == j:
      print(j)
      break
0
1
2
3
4

循环的else语句

​ 循环的else语句与break同时出现当一次循环的进行完成之后,还没有满足执行break的数据时,执行else中的逻辑

for i in range(5): 
  if i == 5:
    print('found 5')
    break
else:		#else属于for循环而不是属于if
  print('not found 5')

/04_break&continue.py"

not found 5

​ 当循环被break跳出后,将不会在执行else中的逻辑语句

for i in range(5): 
  if i == 4:
    print('found 4')
    break
else:
  print('not found 4')

04_break&continue.py"

found 4

match_case语句

match_case和Java的switch比较相似

def http_status(status):
  match status:
    case 400:
      print('Bad Request')
    case 404:
      print('Not Found')
    case _:
      print('REEOR')
status = 400
http_status(status)
status = 404
http_status(status)
status = 444	#当status = 444 时 case中没有匹配的case语句,所以默认执行case _:
http_status(status)

05_match_case语句.py
Bad Request
Not Found
REEOR

特别注意: case _: 相当匹配未成功时默认执行, 在case条件中没有匹配的条件时,默认执行case _: 中的逻辑

匹配模式

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

# 创建一些Point实例
p1 = Point(0, 0)
p2 = Point(0, 5)
p3 = Point(3, 0)
p4 = Point(4, 6)
p5 = Point(1, 2)
p6 = "Not a point"

# 使用where_is函数检查这些点的位置
where_is(p1)  # 输出: Origin
where_is(p2)  # 输出: Y=5
where_is(p3)  # 输出: X=3
where_is(p4)  # 输出: Somewhere else
where_is(p5)  # 输出: Somewhere else
where_is(p6)  # 输出: Not a point

05_match_case语句.py
Origin
Y=5
X=3
Somewhere else
Somewhere else
Not a point
  1. 字面量模式:匹配特定的值。

    match value:
        case 42:
            print("The answer is 42")
    
  2. 变量模式:将匹配到的值赋给变量。

    match point:
        case Point(x=x, y=y):
            print(f"X={x}, Y={y}")
    
  3. 通配符模式:匹配任何值。

    match value:
        case _:
            print("Any value")
    

守卫字句

我们可以为模式添加 if 作为守卫子句。如果守卫子句的值为假,那么 match 会继续尝试匹配下一个 case 块。注意是先将值捕获,再对守卫子句求值

match point:
    case Point(x, y) if x == y:
        print(f"Y=X at {x}")
    case Point(x, y):
        print(f"Not on the diagonal")

简单理解: 在判断case匹配的条件时 要先经过if 如果if的返回值为真,才能继续匹配case中的条件

num = 4
match num:
  case 4 if False:		#if 为假所以直接跳过匹配 输出case _
    print('success')
  case _:
    print('not found')
    
    /05_match_case语句.py
not found
num = 4
match num:
  case 4 if False:		#if 为真 则继续匹配case = 4
    print('success')
  case _:
    print('not found')
    
    /05_match_case语句.py
success
posted @   静香还需努力  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示