百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

【Python3.13】官网学习之控制流(python 控制流)

itomcoil 2025-07-01 20:20 12 浏览

if

if语句是最常见的控制流:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More

for

for语句用来遍历:

# Create a sample collection
users = {'Hans': 'active', ''Eléonore': 'inactive', '景太郎': 'active'}

# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]

# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status

range

range函数生成数字序列:

>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
>>> sum(range(4)) # 0 + 1 + 2 + 3
6

值得注意的是,range函数的返回类型并不是list类型,而是range对象<class 'range'>

虽然它看起来像列表,但实际上它是一个更高效的内存对象,只在需要时生成序列中的数字。例如:

  • range(5) 返回 range(0, 5)
  • type(range(5)) 返回<class 'range'>

如果需要列表,可以使用list()函数进行转换:list(range(5))会返回[0, 1, 2, 3, 4]。

break和continue

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(f"{n} equals {x} * {n//x}")
... break
...
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3
>>> for num in range(2, 10):
... if num % 2 == 0:
... print(f"Found an even number {num}")
... continue
... print(f"Found an odd number {num}")
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

else

这里的else不是if的else,而是在for循环或者while循环中的else:

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

在for循环中,循环结束时,会执行else。在while循环中,循环条件变为false后,会执行else。比如执行了break就不会执行else,没有执行break就会执行else。

pass

pass什么都不做,可以在写代码时临时占个位置:

class MyEmptyClass:
pass
def initlog(*args):
pass # Remember to implement this!

match

match语句跟C、Java的switch语句有点像,跟Rust、Haskell的模型匹配有点像。

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

注意最后一个case的_是通配符,能匹配任何值。

多个值可以用或:

case 401 | 403 | 404:
return "Not allowed"

也能匹配元组并解包:

# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")

还能匹配类对象:

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")

可以通过设置类的__match_args__特殊属性来定义模式匹配时的位置参数顺序。例如:

from dataclasses import dataclass

@dataclass
class Point:
x: int
y: int
__match_args__ = ("x", "y") # 定义模式匹配时的参数顺序

# 以下三种模式匹配方式是等价的:
point = Point(1, 2)

match point:
case Point(1, var): # 使用位置参数
print(f"y is {var}")
case Point(x=1, y=var): # 使用关键字参数
print(f"y is {var}")
case Point(y=var, x=1): # 使用关键字参数
print(f"y is {var}")
case Point(1, y=var): # 混合使用
print(f"y is {var}")

当设置了__match_args__后,模式匹配会按照指定的顺序(x, y)来解析位置参数。这在处理复杂数据结构时能提供更灵活的模式匹配方式。

case还能加if:

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")

元组和列表模式可以匹配任意序列(除了迭代器和字符串),这与解包赋值的行为一致。示例:

def check_sequence(seq):
match seq:
case [1, 2, *rest]: # 匹配任何以1,2开头的序列(除迭代器和字符串)
print(f"匹配列表/元组,剩余元素: {rest}")
case (1, 2, *rest): # 与列表模式效果相同
print(f"匹配元组/列表,剩余元素: {rest}")
case _:
print("不匹配")

check_sequence([1, 2, 3, 4]) # 匹配
check_sequence((1, 2, 5, 6)) # 匹配
check_sequence(range(1, 100)) # 不匹配(迭代器)
check_sequence("1234") # 不匹配(字符串)

enum的match:

from enum import Enum
class Color(Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'

color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))

match color:
case Color.RED:
print("I see red!")
case Color.GREEN:
print("Grass is green")
case Color.BLUE:
print("I'm feeling the blues :(")

补充下,使用Enum枚举类相比直接定义类变量有以下主要优势:

  1. 类型安全:Enum成员是单例的,确保不会创建重复值,而类变量可以被随意修改

  2. 防止值冲突:Enum会自动处理重复值问题,比如:

    class Color(Enum):
    RED = 1
    CRIMSON = 1 # 会被视为RED的别名
  3. 迭代支持:Enum类可以直接迭代所有成员

    for color in Color:
    print(color)
  4. 值验证:Enum会自动验证值的唯一性,防止意外覆盖

  5. 功能扩展:Enum提供了额外方法如:

  • Color.RED.name 获取成员名称
  • Color.RED.value 获取成员值
  • Color['RED'] 通过名称访问成员
  • 语义明确:明确表达了这是一组有限的、预定义的常量集合

  • 防止实例化:Enum类不能被实例化,保证了常量使用的正确性

  • 函数

    关于函数,已经在Python入门系列和进阶系列文章介绍了,这里摘取一些官网有意思的点。

    、函数如果没有return语句,实际上也会返回None:

    >>> fib(0)
    >>> print(fib(0))
    None

    而对于迭代器来说,迭代器协议要求迭代器必须实现__iter__()__next__()方法。当迭代器耗尽时,next()方法会抛出StopIteration异常,而不是返回None。这是迭代器与普通函数返回值的一个重要区别。

    比如:

    def my_range(n):
    i = 0
    while i < n:
    yield i
    i += 1
    for num in my_range(3):
    print(num) # 输出0,1,2
    gen = my_range(3)
    print(next(gen)) # 0
    print(next(gen)) # 1
    print(next(gen)) # 2
    print(next(gen)) # 抛出StopIteration异常,而不是返回None

    这与普通函数返回None的行为形成对比,展示了Python中不同的控制流机制。

    、默认参数值在函数定义时只被求值一次。当默认参数是可变对象(如列表、字典或类实例)时,这个特性会导致默认参数在多次函数调用间共享状态。比如:

    def f(a, L=[]):
    L.append(a)
    return L

    print(f(1))
    print(f(2))
    print(f(3))

    输出:

    [1]
    [1, 2]
    [1, 2, 3]

    如果不想共享状态,可以这样写:

    def f(a, L=None):
    if L is None:
    L = []
    L.append(a)
    return L

    、函数参数可以是positional-only或keyword-only:

    def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
    ----------- ---------- ----------
    | | |
    | Positional or keyword |
    | - Keyword only
    -- Positional only

    示例:

    def standard_arg(arg):
    print(arg)

    def pos_only_arg(arg, /):
    print(arg)

    def kwd_only_arg(*, arg):
    print(arg)

    def combined_example(pos_only, /, standard, *, kwd_only):
    print(pos_only, standard, kwd_only)

    参考资料:

    https://docs.python.org/3.13/tutorial/controlflow.html

    相关推荐

    selenium(WEB自动化工具)

    定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

    开发利器丨如何使用ELK设计微服务中的日志收集方案?

    【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

    高并发系统设计:应对每秒数万QPS的架构策略

    当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

    2025 年每个 JavaScript 开发者都应该了解的功能

    大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

    JavaScript Array 对象

    Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

    Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

    刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

    动力节点最新JavaScript教程(高级篇),深入学习JavaScript

    JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

    一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

    当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

    「晚安·好梦」努力只能及格,拼命才能优秀

    欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

    JavaScript 中 some 与 every 方法的区别是什么?

    大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

    10个高效的Python爬虫框架,你用过几个?

    小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

    12个高效的Python爬虫框架,你用过几个?

    实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

    pip3 install pyspider报错问题解决

    运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

    PySpider框架的使用

    PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

    「机器学习」神经网络的激活函数、并通过python实现激活函数

    神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...