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

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

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

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

    相关推荐

    CentOS7服务器,这样搭建Tensorflow很快!我可以提前去吃饭了

    CentOS7搭建Tensorflow框架凡是我相信的,我都做了;凡是我做了的事,都是全身心地投入去做的。WhateverIbelieved,Idid;andwhateverIdid,...

    python2.0和python3.0的区别(python2.7和3.7哪个好)

    Python3.0是Python语言的一次重大升级,与Python2.x系列存在许多不兼容的改动。以下是两者核心区别的全面总结,按重要性和使用频率排序:一、最关键的破坏性变更特性Pyth...

    体验无GIL的自由线程Python:Python 3.13 新特征之一

    全局解释器锁(GIL,GlobalInterpreterLock)是Python中备受争议的特性之一。它的主要作用是确保Python是一种线程安全的编程语言,防止多个线程同时访问和修改同一...

    Python 3.8异步并发编程指南(python异步调用)

    有效的提高程序执行效率的两种方法是异步和并发,Golang,node.js之所以可以有很高执行效率主要是他们的协程和异步并发机制。实际上异步和并发是每一种现代语言都在追求的特性,当然Python也不例...

    Python测试框架pytest入门基础(pytest框架搭建)

    Pytest简介Pytestisamaturefull-featuredPythontestingtoolthathelpsyouwritebetterprograms.T...

    Python学不会来打我(8)字符串string类型深度解析

    2025年全球开发者调查显示,90%的Python项目涉及字符串处理,而高效使用字符串可提升代码效率40%。本文系统拆解字符串核心操作,涵盖文本处理、数据清洗、模板生成等八大场景,助你掌握字符串编程精...

    windows使用pyenv安装多python版本环境

    官方的介绍。pyenvletsyoueasilyswitchbetweenmultipleversionsofPython.It’ssimple,unobtrusive,an...

    Python 中 base64 编码与解码(Python 中 base64 编码与解码生成)

    base64是经常使用的一种加密方式,在Python中有专门的库支持。本文主要介绍在Python2和Python3中的使用区别:在Python2环境:Python2.7.16(d...

    Python项目整洁的秘诀:深入理解__init__.py文件

    当你发现项目中import语句越来越混乱时,问题可能出在缺少这个关键文件上作为一名Python开发者,我曾深陷项目结构混乱的困境。直到真正理解了__init__.py文件的价值,我的代码世界才变得井然...

    如何把一个Python应用程序装进Docker

    准备容器无处不在,但是如何在Docker容器中运行Python应用程序呢?这篇文章将告诉你怎么做!如果您想知道,这些示例需要Python3.x。在深入讨论容器之前,让我们进一步讨论一下我们想要封装的...

    python中数值比较大小的8种经典比较方法,不允许你还不知道

    在Python中比较数值大小是基础但重要的操作。以下是8种经典比较方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符Python提供6种基础比较运算符:a,b=5,3...

    Python程序员必看3分钟掌握if语句10个神技,第5个99%的人不知道

    同事因为写错一个if被开除?全网疯传的Python避坑指南,看完我连夜改了代码!一、新手必踩的3大天坑(附救命代码)技巧1:缩进踩坑事件ifTrue:print("这样写必报错!...

    为什么Python里遍历字符串比列表慢?3个底层原因揭秘

    用字符串处理文本时,你可能正悄悄浪费性能。在日常Python开发中,我们经常需要遍历字符串和列表。但你是否注意过,当处理海量数据时,遍历字符串的速度明显比列表慢?这背后隐藏着Python设计的深层逻辑...

    记录Python3.7.4更新到Python.3.7.8

    Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...

    Python3中最常用的5种线程锁你会用吗

    前言本章节将继续围绕threading模块讲解,基本上是纯理论偏多。对于日常开发者来讲很少会使用到本章节的内容,但是对框架作者等是必备知识,同时也是高频的面试常见问题。私信小编01即可获取大量Pyth...