Python: MIT6.100L Note(持续更新)
Python: MIT6.100L Note
Name: MIT6.100L: Introduction to CS and Programming using Python
Instructor: Prof. Ana Bell
Time: Fall 2022
Editor: Jimmy_Chen
声明:本文的大部分 code 基本上是上课笔记+个人心得的部分补充。
- 具体课件可以查看
/MIT6_100L_PPT里的文件包。 - 课程官网:https://ocw.mit.edu/courses/6-100l-introduction-to-cs-and-programming-using-python-fall-2022/pages/materials-by-type/
- 食用指南:https://k14eszn58mj.feishu.cn/docx/NFxmd1JxPodkWjxeuHIcSK5Qnag
- 了解更多:https://csdiy.wiki/%E7%BC%96%E7%A8%8B%E5%85%A5%E9%97%A8/Python/MIT6.100L/#_1
说在前面: 你可以去 review 别人的项目看怎么写,但真正要做的是上手。 要知其然所以然,没有了解业务目的的情况下去盲目学习大项目没有任何意义。 先了解立意是什么、做了什么、为什么这么写,怎么做才是 reviw 别人代码的最后一环。
Lecture 1: Introduction to CS and Programming Using Python
1.1 Types of knowledge
- Declarative knowledge is statements of fact
- Imperative knowledge is a recipe or “how-to”
Programming is about writing recipes to generate facts. Computer needs recipes.
1.1.1 Numerical example:
- square root of a number
xisysuch thaty*y = x - for computer, there is a recipe:
start with a guess,
g- if
g*gis close enough tox, stop and saygis the answer - otherwise make a new guess by averaging
gandx/g - using the new guess, repeat process until close enough
- if
遵从这个“recipe”算法,我们可以逐渐逼近正确答案:
| g | g*g | x/g | (g+x/g)/2 |
|---|---|---|---|
| 3 | 9 | 16/3 | 4.17 |
| 4.17 | 17.36 | 3.837 | 4.0035 |
如果希望计算结果与实际值的差距在非常小的范围(例如$10^{-6}$ ~ $10^{-7}$的误差范围内),那么就要循环这个过程多几次。
1.2 Algorithms are recipes, and recipes are algorithms.
For An Algorithm:
- sequence of simple steps
- flow of control proces that specifies when each step is executed (not linearly but change the flow)
- a means of determining when to stop (closed enough)
1.3 COMPUTERS are MACHINES that EXECUTE ALGORITHMS.
Two things computers do:
- Performs simple operations 100s of billions per second!
- Remembers results 100s of gigabytes of storage!
- 电脑需要被告知做出决策,否则无法主动做出决策。电脑根据我们所告知他们的指令进行一系列的操作并执行,这是我们可以做的事(然而近年来的人工智能,或许人的主观控制电脑或许将变得没有那么必要)。
如上所说的,计算机可以存储 GB 或 TB 量级的数据,这不是我们人类可以轻易做到的事情。
What kinds of calculations?
- Built-in to the machine, e.g., +
- Ones that you define as the programmer.
了解一些计算机的历史:
Fixed program computer
- Fixed set of algorithms.
- What we had until 1940’s. 在1940年代之前,有一种叫做固定程序计算机的设备(称为 fixed program computers),烧录了固定的程序,就像便携式的计算器一样。每个按钮都会对应不同的操作。但无法将所有这些操作存储起来,以便后续重复使用,你必须每次都重新输入这些操作。
Stored program computer
- machine stores and executes instructions. 在1940年代之后,出现了存储程序计算机开始出现,他们可以将指令存储为数据,然后有一种特殊的程序叫做解释器,用来执行这些指令(见stored program computer)。
Key insight: programs are no different from other kinds of data.
1.4 Stored program computer
- sequence of instructions stored inside computer
- built from predefined set of primitive instructions
- arithmetic and logical
- simple tests
- moving data
- special program (interpreter) executes each instruction in order
- use tests to change flow of control through sequence.
- stops when it runs out of instructions or executes a halt instruction.
解释器用来执行这些指令,它自身知道如何按照简单的步骤序列执行操作。当程序命令它跳转到另一个位置时,它就会执行这些指令。 而执行的指令就包括算数、逻辑操作,比如:加法、减法,以及简单的测试。比如检查两个值是否相等,还有数据移动,比如将一个值存储到不同的内存位置。
简单来说,计算机有:
- 存储数据的内存 memory (有一堆内存位置,并在每个内存位置预先存储了一些值,例如3456有
3、3457有5等等) - 执行操作的算术逻辑单元 arithmetic logic unit, ALU (do primitive ops, 知道加减)
- 控制单元 control unit (program counter), 其中设置了程序计数器(这个计数器用来存储正在执行的指令的位置,也就是说,它指示了程序当前执行到哪一步。所以程序计数器实际上是用来跟踪程序的执行位置)
执行一个程序的简单示意:(建议看讲义 \MIT6_100L_PPT\mit6_100l_f22_lec01.pdf 里的流程图 p.17-24)

举个例子,当我们运行一个简单的程序的时候:

解释器解析运行的程序内
input的内容解释器先看到第一个指令,例如
Add34563457.解释器执行的结果就是:控制单元找到这些内存位置,而内存在
3456处 预存了3;3457处 预存了4, 然后取出3与4,再将其发送给 算术逻辑单元 ALU
ALU 懂得如何处理
Add加法,得到7将结果发送回去给 控制单元紧接着,解释器执行控制单元内的下一个指令,就是将其刚刚得到的
7作store3458的操作发送给内存, 即控制单元让7这个值存储在了内存的3458处.
同样的过程,完成了
7891的计算(这里假定算出来的结果也是在内存的7891位置存储7)

接着下一条解释器执行指令
compare34587891,控制单元将其指令发送给 ALU,ALU 再次比较两者,由于都是7, 所以判断相等。输出的内容如果是
0表示false, 如果是1表示true,这里将 相等 的结果true发送给内存
控制单元执行最后一步操作,
print结果,从内存的存储位置中拿到了true的结果,于是打印出来outputoutput显示true
note:这个例子(模型)是非常高维度 (high level) 的概述。如果按这种方式来编写开发程序,将十分的繁琐和低效。
1.5 Basic primitives
- Alan Turing (艾伦·图灵) showed that you can compute anything with a very simple machine with only 6 primitives: left, right, print, scan, erase, no op
- 图灵指出,实际上你可以使用更基本的 原语 (basic primitives) 来进行计算,而不仅仅是局限于加法、减法。他提出你可以用一种带子 type,有六种基本的操作(向左移动带子
left、向右移动带子right、读取带子上的值scan、向带子上写入值print、擦除带子上的值erase,以及不进行任何的操作no operations)。 - type 是图灵机的工作原理中的一种概念,它类似于一条无限长的纸带,纸带上有一系列格子,每个格子都可以存储一个符号(通常是
0或1),图灵机可以在纸带上读取、写入和擦除符号,并按照预先设定的规则进行移动。 - 图灵提出上述的观点本质上表明:任何一种编程语言中可以计算的东西,在任何其他编程语言中同样可以计算。Anything computable in one language is computable in any other programming language.

- Real programming languages have:
- More convenient set of primitives
- Ways to combine primitives to create new primitives
由上述观点我们可以知道,如果我们有一些用 Java 编写的程序,即便程序的内容十分的冗杂,但本质上就是由上述的六种 basic primitive 组成。所以若我们将程序化简为这六种原语操作,我们可以在完全不同的编程语言中重构出相同的程序。
1.6 Aspects of languages
在本门课程中,我们将使用 Python 提供的原语,因为它们更加方便,可以更快地完成更多任务。 因此一旦我们在一门语言中有了这些基本原语,我们就可以开始构建语言的语法。
在下面的例子中,我们将英语和原语进行对比,来体会他们的不同之处。
Primitive constructs
- English: words (英语的原语可能是从 字母-单词-词组-句子-文章 而堆砌成)
- Programming language: numbers, strings (sequences of characters), simple operators (like addition, multiplication, devision, checking for the equality, checking for something is greater than 加减乘除以及检查哪个值相等或更大)
Syntax
- English:
"cat dog boy"not syntactically valid"cat hugs boy"syntactically valid
In English, having something like noun, noun and noun doesn’t make any sense. But noun verb noun is syntactically valid. Similarly, in programming languages, we can have two objects kind of side by side:
- Programming language:
"hi"5not syntactically valid. It has no meaning in Python."hi"*5syntactically valid. What we have to do is we have to add an operatoor in between these two objects.
In Python, the meaning to "hi"*5" is I want to repeat the sequence of characters hi five times.
构建了符合语法的句子和表达式之后,就可以来谈谈静态语义
Static semantics: which syntactically valid strings have meaning 既要正确,还要有意义。
- English: “I are hungry” -> syntactically valid, but static semantic error
- PL: “hi”+5 -> syntactically valid, but static semantic error,显然加五没有多大意义
在编程语言中,根据你所使用的编程语言而有所不同,static semantic 会有所不同。
Semantics: the meaning associated with a syntactically correct string of symbols with no static semantic errors.
需要注意的是,在英语中,例如: the chicken is ready to eat means let's eat this chicken or the chicken wants to eat something 。English can have many meanings.
Programs have only one meaning! (这是由于计算机、机器和语言都是严格遵循设定的指令) But the meaning may not be what programmer intended.
1.7 Where things go wrong
syntactic errors
- comman and easily caught (e.g., syntactic errors, spelling errors, indentation erros 缩进错误)
static semantic errors
- some languages check for these before running program
- can cause unpredictable behavior
no linguistic errors, but different meaning than what programmer intended (即想做的事和程序所执行的事不一样,这是常见的问题)
- program crashes, stops running
- program runs forever
- program gives an incorrect answer
1.8 Python programs
python 是一种解释器。
- A program is a sequence of definitions and commands
- Definitions evaluated
- Commands executed by Python interpreter in a shell (e.g., bash or zsh console)
- Commands (statements) instruct interpreter to do something
- Can be typed directly in a shell or stored in a file that is read into the shell and evaluated
- Problem Set 0 will introduce you to these in Anaconda
1.9 Programming environment: anaconda & miniforge
1.9.1 关于 anaconda
Anaconda 是 python 环境/包管理工具,经常会与 vs code 配合使用。并且商用。
conda是 包管理工具: 它是一个在终端里执行的命令,负责帮你下载软件、解决依赖冲突、创建虚拟环境。Anaconda是一辆出厂自带了几百个包裹的重型卡车: 它里面装了conda发动机,但也塞满了几 GB 你可能永远用不到的数据分析库。Miniforge是一辆极其轻量级的超级跑车: 它里面同样装了 conda 发动机,但车厢是空的,并且它的导航默认设定指向了最大的开源科学软件仓库——conda-forge。
anaconda 其界面的主要分布: code editor (left side) + shell / console (right side)
如果为了快速检查某件事情,而不是想写一个程序再运行,而仅仅只是想检查一个简单的命令以确保能执行所期望的事情的时候,可以直接在 shell 里输命令行(before coding)。
- 为什么 MIT 官方会推荐 Anaconda?
这是为了降低新生的入门门槛。 Anaconda 提供了一个“傻瓜式的一键安装包”。装完之后 Python 有了,科学计算包有了,Spyder 编辑器也有了,甚至连环境变量都不用管。如果此时你去装一个好几个 GB 的 Anaconda,它会把臃肿的 Spyder 强塞给你,并且粗暴地重写你的 ~/.zshrc.
- conda 的衍生物,以及一些小知识: anaconda(商用要钱); condaforge(社区版); miniconda (anaconda 的 mini 版,只有 CLI); miniforge (condaforge 的 mini 版,现在和 mambaforge 合并,因此 miniforge = miniconda + mamba ); mambaforge (早年有个 C++ 重写的 conda 命令,解析依赖和下载比原版的 conda 快,但现在已经合并,所以 mambaforge 和 miniforge 是一个东西); mamba;
1.9.2 更好的、轻量的替代品 —— Miniforge
完全没必要安装体积庞大的完整版 Anaconda,但强烈建议安装它的轻量化替代品——Miniforge。
考虑到后续可能会折腾 AlphaFold 3,或者用 Python 脚本去提取和分析 GROMACS 的分子动力学轨迹数据,绝对需要用到 conda 这个环境管理器。原因非常如下:
解决 M4 芯片的编译噩梦: 很多计算化学和生物信息学的核心库(比如 rdkit、MDAnalysis 或 OpenMM),底层涉及大量的 C/C++ 代码。在 Apple Silicon 芯片上直接用普通 pip 安装,极大概率会遇到编译报错。而 conda 的社区频道(conda-forge)专门为 M 系列芯片提供了完美的预编译包,一键安装,绝不出错。
虚拟环境的物理隔离: 跑特定的计算程序(比如 AlphaFold 3 的某些依赖)往往需要绑定某个较老的 Python 版本。用 conda 可以帮你创建无数个互相平行的“沙盒环境”(比如一个装 Python 3.9,另一个装 3.10),彻底避免不同项目之间的版本冲突,也不会污染你系统级的 Python 3.14。
Miniforge 是 Anaconda 的开源纯净版,初始大小只有几十兆。它自带了 conda 命令,并且默认连接对科学计算最友好的 conda-forge 软件源。
在 VS Code 里,它们的配合堪称绝杀: 只需要在 VS Code 的插件市场安装微软官方的 Python 插件。之后不管你创建了多少个虚拟环境,只要点击 VS Code 界面右下角的 Python 版本号,它就会弹出一个列表。你可以极其丝滑地在你的 Homebrew Python 3.14、VMD 数据处理环境、或者 AlphaFold 专属环境之间一键切换。
1.9.3 如何安装 miniforge?
- macOS 安装与启动 miniforge (基于 Homebrew) 如果已经有了完善的 Homebrew 环境,这是最优雅、最干净的方式。
- 一键安装: 在你的终端里直接运行:
brew install miniforge
往往会安装到
==> Linking Binary 'conda' to '/opt/homebrew/bin/conda'
==> Linking Binary 'mamba' to '/opt/homebrew/bin/mamba'
- 初始化(挂载到 Zsh): 安装完成后,需要让你的 Zsh 终端认识 conda 命令:
conda init zsh
- 启动生效: 重启终端,或者直接运行以下命令让配置立刻生效:
source ~/.zshrc
生效后,你的终端提示符最左边会出现一个 (base),代表你已经成功进入了 Miniforge 的基础环境。 (如果是安装了 oh my zsh,则有时候会在右侧,并提示 Py base)
- 🐧 Linux 安装与启动 miniforge (基于官方脚本).
直接通过命令行下载官方的自动化安装脚本。
- 智能下载脚本: 这条命令极其好用,它会自动检测你 Linux 服务器的系统类型和 CPU 架构(x86 还是 ARM),并下载对应的最新版:
curl -L -O "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
- 运行安装程序:
bash Miniforge3-$(uname)-$(uname -m).sh
执行后会出现协议(按 Enter 往下翻,输入 yes 同意),然后会问你安装路径(默认在 ~/miniforge3,直接回车即可)。
在 wsl2 上安装 miniforge
- 如果你安装在 wsl2 上的 linux 中,则往往会因为系统过于简略少了很多包,导致报错:
Miniforge3-Linux-x86_64.sh: line 39: awk: command not found需要手动补齐。
sudo dnf install gawk tar bzip2 findutils
若安装时网络切换,如切换代理 vpn 等,则 wsl2 会受到影响。Could not resolve host: mirrors.fedoraproject.org 指出你的系统现在无法把域名转换成 IP 地址。
这是 WSL2 架构下最臭名昭著的经典 DNS 解析丢失 Bug。由于 WSL2 是基于 Hyper-V 虚拟网络运行的,Windows 宿主机和 WSL 虚拟子系统之间的 DNS 转发经常会因为网络环境切换(比如你连了 Wi-Fi、插拔了网线,或者在 Windows 上开启了某些代理/VPN 软件)而突然中断。
你可以通过以下步骤,手动强制为 WSL2 指定可靠的 DNS 来解决这个问题:
- 删除系统自动生成的无效 DNS 配置文件(它通常是个软链接) sudo rm /etc/resolv.conf
- 重新创建一个新的配置文件,并写入通用的公共 DNS(如 Google 和 Cloudflare 的 DNS) sudo bash -c ’echo “nameserver 8.8.8.8” > /etc/resolv.conf' sudo bash -c ’echo “nameserver 1.1.1.1” » /etc/resolv.conf'
- 再次尝试安装 DNS 修改是瞬间生效的,不需要重启。你现在可以直接重新运行刚才的安装命令。
- 初始化(挂载到 Shell):
安装的最后一步,它通常会问你:Do you wish the installer to initialize Miniforge3 by running conda init?
一定要输入 yes。
(如果手滑错过了,也可以手动执行:~/miniforge3/bin/conda init bash,如果你在 Linux 上也配了 zsh,就把 bash 换成 zsh)
一般程序会安装到 /home/jim/miniforge3。
安装结束之后则会提示:
# >>> mamba initialize >>>
# !! Contents within this block are managed by 'mamba shell init' !!
export MAMBA_EXE='/home/jim/miniforge3/bin/mamba';
export MAMBA_ROOT_PREFIX='/home/jim/miniforge3';
__mamba_setup="$("$MAMBA_EXE" shell hook --shell bash --root-prefix "$MAMBA_ROOT_PREFIX" 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__mamba_setup"
else
alias mamba="$MAMBA_EXE" # Fallback on help from mamba activate
fi
unset __mamba_setup
# <<< mamba initialize <<<
Thank you for installing Miniforge3!
- 启动生效:
source ~/.bashrc # 如果你是 zsh 用户,则是 source ~/.zshrc
同样,终端最左侧出现 (base) 即代表成功。
- 其他的提醒事项
当你成功启动并在终端看到 (base) 后,强烈建议执行下面这行命令(macos 或者 linux 都适用):
conda config --set auto_activate_base false
# 如果提示报错如下:
WARNING conda.cli.condarc:set_key(484): Key auto_activate_base is an alias of auto_activate; setting value with latter
# 有些版本则是中间参数直接改为 --set auto_activate 即可,故改为:
conda config --set auto_activate false
需要使用 conda 时,再敲 conda activate,用完conda deactivate退出。
当你敲下上述命令时,Conda 实际上并没有去改 ~/.zshrc,而是在你的用户根目录(~)下新建或修改了一个名叫 .condarc 的隐藏配置文件,并在里面写上了这样一行规则:auto_activate_base: false。
即无论你打开什么终端,Conda 在底层初始化时都会去读取这个 .condarc 文件。一旦看到 false,它就会乖乖“潜水”,绝对不会强行把 (base) 塞到之前 zsh 配置的 Powerlevel10k 提示符前面。
它的作用就是阻止 Miniforge 每次打开终端时自动进入 (base) 环境。由于本地有自己装好的原生 Python 3.14,我们希望终端保持绝对的清爽。
只有当你想写作业,或者跑特定计算任务时,才手动输入 conda activate 来呼唤它,用完后输入 conda deactivate 退出。这才是最顶级、最干净的环境管理习惯。
1.9.4 结合 vs code/conda 的使用教程以及一些常识
conda 的基本使用教程
- 创建沙盒: 永远不要在 (base) 环境里乱装东西,养成“一个项目建一个专属沙盒”的习惯。
conda create -n mit python=3.14 # 创建一个名为 mit 的沙盒
# -n 代表 name,后面紧跟着给环境起的名字
# python=3.14 告诉它在这个沙盒里放入什么版本的 Python。执行后它会询问你是否确认安装一堆基础依赖,输入 y 回车即可。
- 激活和退出沙盒 :
conda activate mit
视觉反馈: 执行完这句后,你会发现你的 Powerlevel10k 终端提示符发生了变化——通常在最左侧或最右侧,会亮起一个包含如 Py mit 字样的标识。这代表你现在敲击的任何 python 或 pip 命令,都只在这个沙盒内部生效,绝对不会影响你系统原本的 Python 3.14。
如果要退出沙盒,只需要执行(下次重新 activate 会回到之前这个沙盒):
conda deactivate
- 管理沙盒:
查看建了多少个沙盒,列出所有环境:
conda env list
它会列出一个清单,把你的 base 等等环境全都展示出来,并且用一个星号 * 告诉你当前正在哪个环境里。
- 销毁沙盒:
conda env remove -n mit # 摧毁一个名为 mit 的沙盒环境
- 安装工具包:
进入沙盒后,你就可以 肆意安装 需要的包了。这也是 Miniforge 相比官方 Anaconda 最强大的地方:它默认使用 conda-forge 软件源。并且 conda-forge 社区为 Apple Silicon (ARM64) 架构预编译了极其丰富的科学计算包。
以后如果你需要处理复杂的计算化学数据,只需输入:
conda install numpy pandas matplotlib rdkit # rdkit是化学信息学工具,matplotlib可以用于绘制图片
它会自动帮你找到最契合 M芯片 性能的底层二进制版本,彻底告别编译报错。
- 在 VS Code 中召唤沙盒
既然沙盒建好了,我们怎么让 VS Code 里的代码也跑在这个环境里呢?具体如下:
在 VS Code 里随便打开或新建一个 Python 文件(比如 test.py)。
按下万能的 Cmd + Shift + P 打开命令面板。
输入并选择 Python: Select Interpreter (Python: 选择解释器)。 在弹出的列表里,你一眼就会看到带有 (‘mit’: conda) 字样的选项,点击选中它。当然,你也可以鼠标点击右下角的 select interpreter 来进行选择。 一般会出现 global 的,conda 的,来自 homebrew 的都有。
此时,VS Code 的右下角状态栏就会显示你选中的环境。你再右键使用 Code Runner 运行代码时,VS Code 就会极其聪明地去调用你这个沙盒里的 Python 了,其 python 文件也仅仅在那个沙盒里运行。
- 我们上述使用的 Select Interpreter(选择解释器)唯一任务就是告诉 VS Code 的底层代码补全工具(Pylance)以及 右键的运行按钮时,指令去具体的路径下找 Python 来跑代码【结果输出在 vs code 下面的 outputs】。
- 而在新版本的 vscode 中,微软推出了新的过渡期的功能 —— Select a Python Environment(选择 Python 环境)。不满足于仅仅“指定路径”,它想要打造一个可视化的沙盒控制中心。在这个新机制下,你甚至可以在 VS Code 的左侧边栏用鼠标点点点,就能直接创建 Conda 沙盒、删除沙盒、查看里面安装了哪些包。 不过这两者在底层是100% 双向绑定的,往往不冲突。
常见问题:
- 为什么我已经如上选择了
py3.14的沙盒,但在 vs code 的code编辑栏里,以及在terminal里输入print ("hello"),却报错zsh: unknown file attribute: h,然而只有输入python3.14进入之后敲print ("hello")才可以正常打印?
出现这个现象的核心原因,是因为你混淆了计算机里的两个不同概念, zsh 终端 和 python 解释器。
Zsh 终端(操作系统的管家):
当你打开 VS Code 底部的 Terminal,看到 jim@jims-MacBook-Pro ~ % 或者前面带有 (mit6100l) 时,你处于 Zsh 也就是 Shell 的世界。
它听得懂什么: 像 cd(进文件夹)、ls(看文件)、tclsh(启动 Tcl)、python(启动 Python)、conda(管理环境)这些操作系统级别的命令。
它听不懂什么: 它完全不懂 Python 语法。
报错揭秘: 当你在 Zsh 里敲下 print (“hello”) 时,Zsh 蒙了。它以为你要用一个叫 print 的系统命令,而后面的括号 ( ) 在 Zsh 语言里代表“高级文件筛选”。它看到括号里的第一个字母 h,以为你在找某种具有 h 属性的文件,结果找不到,于是报错:zsh: unknown file attribute: h。
Python 解释器(Python 的专属领地):
只有当你输入 python3.14(或者 python3)并回车后,终端的提示符变成了 »>。这时候,你才真正踏入了 Python 的世界。
为什么 VS Code 选了环境也没用?因为在 VS Code 右下角选择了 Python 3.14,这个动作并不会把底部的 Zsh 终端变成 Python 终端。它只是在告诉 VS Code:“如果我点击右上角的播放键(或者右键使用 Code Runner),请帮我在后台用 Python 3.14 把我的代码跑一遍,然后把结果显示出来。”
以后在 VS Code 里写 Python,我们通常不会直接在终端里一行一行敲代码(除非只是为了当计算器测试一下)。一般流程是这样的:
- 写在文件里: 在 VS Code 的编辑区,新建一个文件,命名为 test.py。
- 选择Cmd + Shift + P 打开命令面板,输入并选择 Python: Select Interpreter,选择沙盒,或者是右下角选沙盒环境。
- 输入代码: print("hello")
- 保存文件
- 运行文件:右键点击编辑区,选择 "Run Code"(之前装的 Code Runner 发挥作用了)。
- code runner 配置问题(常见)
我们第一次在 vs code 中运行 .py 经常会见到 code run 发送如下报错:
[Running] python -u "/Users/jim/box/Note/Python/test.py"
/bin/sh: python: command not found
为什么会报错?
仔细看报错信息里的第一行:[Running] python -u ...Code Runner 插件非常机械,它看到是.py文件,就默认向系统发送了python这个指令。但问题在于:
苹果 macOS 系统早就把名叫 python 的老版本(Python 2)彻底删除了。现在系统里默认只有
python3。 Code Runner 默认使用的是非常底层的 /bin/sh 来执行命令,它根本不会去读取咱们之前在 Zsh (~/.zshrc) 里辛苦配置的环境变量。所以它两眼一抹黑,直接报了 command not found。解决方案:
既然咱们已经学过怎么调 Code Runner 运行 Tcl,现在只要用同样的方法,教教它怎么运行 Python 就行。而且,配完之后,它会自动兼容未来所有的 Miniforge 沙盒环境。
请按照以下步骤修改配置:
打开设置文件: 按 Cmd + Shift + P,输入 Open Settings (JSON),选择 “首选项: 打开用户设置 (JSON)”。
修改执行规则:
找到咱们之前写 Tcl 规则的地方,也就是 "code-runner.executorMap",把它补充成下面这样(注意别漏了逗号):
"code-runner.executorMap": {
"tcl": "tclsh",
"python": "$pythonPath -u $fullFileName"
},
添加的这行代码,把原本默认的 python 改成了 $pythonPath。它告诉 Code Runner 用户在 VS Code 右下角选了哪个环境(比如你的 Homebrew 3.14,或者 conda 创造的自定义名称的沙盒),你就用那个环境里的 Python 去跑代码。
1.9.5 推荐安装的 python 库
下面是科研数据处理基础包推荐。
- 最推荐先装这一组
进入你的 conda 沙盒后执行:
conda install -c conda-forge numpy pandas scipy matplotlib seaborn jupyterlab ipykernel openpyxl tqdm
这些是基础盘:
| 库 | 用途 |
|---|---|
numpy | 数组、矩阵、数值计算 |
pandas | 表格数据、CSV、Excel、日志整理 |
scipy | 拟合、积分、信号处理、统计 |
matplotlib | 画图,适合论文图基础处理 |
seaborn | 更方便画统计图 |
jupyterlab | Notebook 环境 |
ipykernel | 让 conda 环境能被 Jupyter 识别 |
openpyxl | 读写 .xlsx |
tqdm | 循环进度条 |
- GROMACS 数据分析推荐
conda install -c conda-forge mdanalysis mdtraj parmed nglview
| 库 | 用途 |
|---|---|
MDAnalysis | 读 .xtc、.trr、.gro、.pdb,做 RMSD、RMSF、距离、接触、氢键等分析 |
mdtraj | 轨迹分析,速度快,API 简洁 |
ParmEd | 处理拓扑、力场、GROMACS/AMBER/CHARMM 格式转换 |
nglview | 在 Jupyter 里交互式看结构和轨迹 |
MDAnalysis 明确支持读取多种模拟软件产生的轨迹,包括 GROMACS、CHARMM、AMBER、NAMD、LAMMPS 等;它也能读取 XTC/TRR 这类 GROMACS 轨迹格式。(docs.mdanalysis.org)
ParmEd 的 parmed.gromacs 模块可以解析 GROMACS topology 和 coordinate files,适合你以后做拓扑检查、格式转换或力场文件处理。(parmed.github.io)
- ORCA / Gaussian 输出文件解析推荐
conda install -c conda-forge cclib ase periodictable
| 库 | 用途 |
|---|---|
cclib | 解析 Gaussian、ORCA 等量化输出文件 |
ase | 结构处理、坐标转换、简单建模、和量化程序联动 |
periodictable | 元素、同位素、原子量等基础数据 |
cclib 是专门用来解析和解释计算化学程序结果的 Python 开源库,文档明确提到支持 Gaussian 09/16 等程序;它也常用于从计算化学 log 文件中提取能量、轨道、振动频率等数据。(cclib.github.io)
- 后期 PySCF 方向
PySCF 我建议用 pip 装在同一个 conda 环境里:
pip install --prefer-binary pyscf
官方文档也推荐非开发者用:
pip install --prefer-binary pyscf
PySCF 的 pip wheel 在多数 Linux 和 macOS 系统上可用。(pyscf.org)
如果你以后要做更完整的量化 Python 工作流,可以再装:
pip install geometric pyberny basis-set-exchange
| 库 | 用途 |
|---|---|
pyscf | Python 量子化学计算框架 |
geometric | 几何优化器,可配合 PySCF |
pyberny | 另一个几何优化工具 |
basis-set-exchange | 下载/转换基组 |
PySCF 本身是通用电子结构平台,支持分子和周期体系、多种 mean-field/post-HF 方法,并且核心计算路径有 C 优化。(arXiv)
- 懒人一条流
进入你的 conda 环境后,先执行这一条:
conda install -c conda-forge numpy pandas scipy matplotlib seaborn jupyterlab ipykernel openpyxl tqdm mdanalysis mdtraj parmed nglview cclib ase periodictable
然后再装 PySCF:
pip install --prefer-binary pyscf
最后测试:
python - <<'PY'
import numpy
import pandas
import scipy
import MDAnalysis
import mdtraj
import parmed
import cclib
import ase
import pyscf
print("numpy:", numpy.__version__)
print("pandas:", pandas.__version__)
print("scipy:", scipy.__version__)
print("MDAnalysis:", MDAnalysis.__version__)
print("mdtraj:", mdtraj.__version__)
print("ParmEd:", parmed.__version__)
print("cclib:", cclib.__version__)
print("ASE:", ase.__version__)
print("PySCF:", pyscf.__version__)
PY
- 最简推荐
conda install -c conda-forge numpy pandas scipy matplotlib jupyterlab openpyxl tqdm mdanalysis mdtraj parmed cclib ase
pip install --prefer-binary pyscf
这套已经足够你处理大部分 GROMACS + ORCA + Gaussian + 后期 PySCF 的数据分析任务。
1.10 Objtect
What exactly do we do when we write a program? A: 创建对象(create object)inside our program,and we’re going to manipulate
- Programs manipulate data objects
- Objects have a type(创建的对象是有类型的) that defines the kinds of things programs can do to them(对象的类型告诉 Python 可以执行哪些操作):
30:- Is a number
- We can add/subtract/mult/div/exp/etc/power(幂次)
Ana(capital A and lowcase A):- Is a sequence of characters (字符的序列,as known as a string 字符串)
- We can grab substrings(例如:获取第一个位置的字符是什么、 中间的字符是什么,字符有多长等等), but we can’t divide it by a number(也不能字符串除以字符串)
Python 使用它来指导你可以对它执行的操作的类型。
Python’s primitives(基本数据类型):numbers, truth values (布尔值, bool), non-scalar :
Scalar (scalar object,标量对象。cannot be subdivided):
- Numbers:
8.3,2(数字本身没有结构) - Truth value:
True,False
- Numbers:
Non-scalar (have internal structure that can be accessed,里头还有可再分的元素):
- Lists
- Dictionaries
- Sequence of characters: “abc”
1.11 The types of the scalar object 标量对象的型
Python 中的基本数据类型如下,这四种都是对象类型:
int– represent integers(整数), ex.5,-100float– represent real numbers(实数), ex.3.27,2.0bool– represent Boolean(布尔类型) valuesTrueandFalse(而且在 python 中这两个必须首字母大写!)NoneType– special and has one value,None
另外,还有 **字面量(literal)**与 标识符(Identifier/变量名) 的概念。
- Tip: Can use
type()to see the type of an object.(type 的类型就是 type) for example:
>>> type(5)
<class 'int'>
>>> type(5.0)
<class 'float'>
# 下面这个例子需要注意的是,True 在 python 中必须首字母大写
>>> type(True) # what you write into python shell
<class 'bool'> # what shows after hitting enter
>>> type(true)
Traceback (most recent call last):
File "<python-input-6>", line 1, in <module>
type(true)
^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?
# 名称错误的报错
# 事实上 type() 本身也是一种 type
>>> type(type(5/2))
<class 'type'>
1.12 Type conversion (Casting)
一旦我们创建了 object,我们可以对这些对象执行的一件事情就是将他们转换成不同的类型。
- Can convert object of one type to another
float(3)casts the int3to float3.0int(3.9)casts (note the truncation!注意截断!) the float3.9to int3(截断并给出整数的版本,并不round四舍五入)str(400)returns'400'(转换成字符串)
- Some operations perform implicit casts(隐式转换)
round(3.9)returns the int4
it’s actually going to round(四舍五入) it to 4.0 and then cast it to an integer! (注意 round(3.9) 是先四舍五入,然后转化成整数,因此结果严格意义来说不会四舍五入成 4.0,而是 4)
需要注意的是,int 在转换字符串的时候也有一定的要求。有些字符串如果内容原先是整数的(我们仅仅谈论字符串文本内容,暂且不论对象类型),可以正常隐式转换。然而,当字符串里的文本内容是浮点数的,这时候进行整数的 casting 会报错:
>>> int("3")
3
>>> int("3.9") # 这时候 str 转 int 会报错!
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
int("3.9")
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.9'
ex_1.1 find the type of:
float(123) # 123.0, float
round(7.9) # 8, integer, int
float(round(7.2)) # 7.0, float
int(7.2) # 7, int
int(7.9) # 7, int
1.13 Expression 表达式
我们在上面讲述了何为 对象 object,而我们可以将他们组合成 表达式 expression。
Syntax for a simple expression:(对象 运算符 对象)
<object><operator><object>
- Combine objects and operators to form expressions
- 3+2
- 5/3
- An expression has a value, which has a type
- 3+2 has value 5 and type int
- 5/3 has value 1.666667 and type float
- Python evaluates expressions and stores the value. It doesn’t store expressions! Python 读取表达式,但是不会将表达式存储在内存中,它是先评估为一个单一的值,然后将其存储在内存中!
>>> 5/2
2.5
>>> type(5/2) # 这个例子表明了组合后的表达式实际上有个对应的值以及相应的 type
<class 'float'>
Big Idea:
Replace complex expressions by ONE value (expressions -> value -> replace) Work systematically to evaluate the expression. A bunch of it doesn’t just have to be object operator object.
ex_1.2
这里需要提醒的一点是: Do computations inside parenthesis first, left to right
>>> 3+2
5
>>> (4+2)*6-1
35
>>> type((4+2)*6-1)
int
>>> float((4+2)*6-1)
35.0
2**3 # 输出结果得到 8
2.0**3 # 得 8.0
1.14 Operator on int and float
ex_1.3 find the values of the following expressions
(13-4) / (12*12) # 这个表达式也可以写成 (13-4)/(12*12),得到值 0.0625
4/2 # 得到 2.0
>>> type(4*3) # 得到了 int 类型
>>> type(4.0*3) # float
int(1/2) # 得到值 0,显然进行了 truncate
5%3 # 得到2
5.0%3 # 得到2.0
>>> type(5%3)
<class 'int'>
>>> type(5.0%3)
<class 'float'>
>>> 5//3
1
>>> 5.0//3
1.0
>>> 2**3
8
>>> 2.0**3
8.0
>>> 2**3.0
8.0
根据上面的结果,我们可以得到一些运算符和输出结果的一些规律:
Table1.1 运算符小结
Question: So why does division always result in a float?
如果除法不这么做,它需要一些额外的步骤,例如判断这是否是一个整数。因此直接给出浮点数会更简单些。此外,在早起的 Python 版本实际上斜杠是整除的,这在程序设计上十分的反直觉,有时程序会出错。It just a design choice on behalf of the programmers. 下面我们将仔细的探讨。
在 Python 3 中,单斜杠
/被称为真除法 (True Division)。无论参与运算的数字是整数还是浮点数,它都会返回一个精确的浮点数 (Floating-point number),所以5 / 3会得到1.6666666666666667。消除隐式的数据丢失(防止 Bug): 在早期的 Python 2,以及像 C语言、Java 甚至你熟悉的 Tcl 中,如果两边都是整数(如 expr 5 / 3),结果会默认截断为
1(这叫整数除法)。但这在实际工程中极易引发不易察觉的逻辑错误(比如计算平均值时精度丢失)。Python 3 的核心哲学是 “Explicit is better than implicit”(显式优于隐式)。设计者认为,数学上的除法本身就是产生分数的,保留数学意义上的精确性是最符合直觉的。若需要截断,则用//而之所以
2/2会得到1.0,这涉及到了类型一致性 (Type Consistency) 与可预测性 (Predictability)。如果 Python 的设计器这样规定:能整除就返回
int,不能整除就返回float。这听起来似乎很智能,但在真实的工程或科学计算中,这将是一个噩梦:- 避免程序隐式崩溃:假设你正在跑一个复杂的数值模拟(比如处理一个巨大的计算矩阵),你的代码里有一步是
A = X / Y。接下来的代码严格依赖A是一个浮点数才能继续进行矩阵的后续运算。如果X和Y恰好碰到了类似2和2这样能整除的极端情况,A 突然变成了一个整数(int)。这时候,下游那些只认浮点数的方法或 C 语言底层的扩展库(比如大规模并行计算时)可能瞬间抛出类型不匹配的错误,或者导致计算精度的隐性崩溃。为了让程序的运行是确定且可控的,Python 规定/的返回类型必须被锁死为float,绝不随运行时的具体数值而摇摆。 - 内存表示的物理隔阂:在内存里,整数
1和浮点数1.0的“长相”是完全不同的:整数1在 Python 中是以任意精度整数的结构存储的。浮点数1.0是严格遵循 IEEE 754 双精度标准 的,它由符号位、指数位和尾数位构成。当你执行2 / 2时,Python 的底层 C 代码(CPython 解释器)会先将两个整数转换为浮点数,执行浮点运算硬件指令,从而保证返回类型是float,最后生成一个符合 IEEE 754 标准的内存对象1.0。它不会多此一举去检查“尾数全是零,要不我把它转回整数吧”,因为类型转换本身也是有性能开销的,为了更好的性能,保留为浮点数也是正常的。
- 避免程序隐式崩溃:假设你正在跑一个复杂的数值模拟(比如处理一个巨大的计算矩阵),你的代码里有一步是
1.15 Simple operations
Parentheses tell Python to do these operations first(Like math!)
Operator precedence without parentheses:
**exponentiation* / %multiplication division percent; executed left to right, as appear in expression+ -addition subtraction; executed left to right, as appear in expression
1.16 Variables
我们在上面了解了简单的对象 object,下面我们要给这些对象进行命名。给冗长的值取一个名字,后续抓取会使得程序更加优雅、简洁以及不易出错。
- Computer science variables are different than math variables!
- Math variables:(是声明式的,declaretive knowledge/statement)
- abstract
- can represent many values
- e.g.,
a + 2 = b - 1x * x = yx represents all square root(但这一个想法在计算机科学中是行不通的)
- CS variables:(不使用 declarative knowledge,我们使用 imperative knowlege。即,我们在计算机科学领域中,我们处理的是一堆赋值语句 a bunch of assignment)
- Is bound to one single value at a given time
- Can be bound to an expression (but expressions evaluate to one value!)
- e.g.,
a = b + 1m = 10 F = m*9.98注意前面都只有一个变量 one variable,后面则接着 one value; 在第二个赋值当中, 首先会对右边的表达其进行 evaluate,最后再绑定给左边的变量名。
So one variable basically maps(映射) or binds(绑定) to one value!
- 需要注意的是,在数学方程中,
x = 6和6 = x是等价的,表示两边相等。但在编程(包括 Tcl 和 Python)中,单等号=不是用来判断相等的(若要判断相等则用==),=是赋值操作符 (Assignment Operator)。此外,像6在 Python 中被称为 整型字面量 (Integer Literal),它是不可变的数据实体本身,而不是一个可以用来贴标签的“标识符”。 - 在 Python 中,变量名不是装数据的“盒子”(这与 C 语言不同),变量名更像是便利贴(Nametag/Reference)。
- 赋值符的严格方向性:赋值语句永远是从右向左执行的。
1.17 Binding variables to values
Binding:指变量绑定
- In CS, the equal sign is an assignment
- One value to one variable name
- Equal sign is not equality, not “solve for x”
- An assignment binds a value to a name:
pi = 355/113(piis variable;355/113is value) 对于该例:- Step1: Compute the value on the right hand side (the VALUE).计算右侧(R-value / 右值),并在内存中创建一个对象。
- note: Value stored in computer memory
- Step2: Store it (bind it) to the left hand side (the VARIABLE)
- Retrieve value associated with name by invoking the name (此后用这个变量名可以触发变量的检索,python 将自动在内存中抓取 evaluated 后的
3.14159...)
- Retrieve value associated with name by invoking the name (此后用这个变量名可以触发变量的检索,python 将自动在内存中抓取 evaluated 后的
- Step1: Compute the value on the right hand side (the VALUE).计算右侧(R-value / 右值),并在内存中创建一个对象。
- 一个常见的问题就是:如果我后续设计的程序重复用到了前面一致的变量名,然而变量名没有设定初始化的情况下(即没有更换绑定,而是沿用了之前别的程序里的赋值),这种是交互式环境里很常见的“隐性状态污染”。
- 删除变量绑定的方法:1. 用
del删除变量绑定 (类似 tcl 中的delete);2. 重启 Python 解释器 / Kernel:- 例如:
del start
del end
# 也可以写成一行:
del start, end
- 查看当前有哪些已经存在了的变量:
- 在交互式 Python 里可以用:
dir()进行查询
- 在交互式 Python 里可以用:
ex_1.4
Which of these are allowed in Python? Type them in the console to check.
>>> x=6 # ok!
>>> 6=x
File "<python-input-1>", line 1
6=x
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
# 语法错误:无法赋值给字面量。等号右边是 x(假设 x 已经定义),等号左边是 6。6 在 Python 中被称为 整型字面量 (Integer Literal),它是不可变的数据实体本身,而不是一个可以用来贴标签的“标识符”。你不能把一个名字(变量)赋值给一个固定的数字。试图把写着 6 的便利贴(但 6 根本不是便利贴,它是一个已经存在的实体气球)贴到另一个气球上。解释器直接罢工:这是语法错误。
>>> x*y=3+4
File "<python-input-2>", line 1
x*y=3+4
^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
# 显然,在 python 中 * 是特别的运算符,因此左侧不能被认为是通识符。
>>> x=a+3
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
x=a+3
^
NameError: name 'a' is not defined
# 说明右侧的值若在计算之前有变量,则应定义好变量的值,否则报错
>>> xy=3+4 # ok!
print(xy)
7
上面这些和 tcl 语言里万物皆为单词的思想截然不同!我们之前学过在 tcl 语言中,这个是可以直接表达的:
set x*y 3+4
3+4
原因不难理解,在 python 中,x*y 有一个操作符operator,运算符号是特殊的,而 xy 则是单纯的字符串 string。下面,你可以尝试在终端里输入:
'xy' # 注意这里会有特殊的颜色,并且返回 'xy',注意不是反引号`!
'x*y' # 返回 'x*y'
>>> 'xy' = 3+4
File "<python-input-10>", line 1
'xy' = 3+4
^^^^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
>>> 'x*y'=3+4
File "<python-input-7>", line 1
'x*y'=3+4
^^^^^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
# 这里先右边计算得出 7,但左边的 'xy' 此时是一个·字符串字面量 (String Literal)·。你不能强迫字符串 'xy' 去作为 变量名 来指向数字 7。
借由上面的例子,我们可以知道:变量名不是随便取的。像含有特别的运算符、字符串字面量 (String Literal)、整型字面量 (Integer Literal)
1.18 Abstracting expressions
- why give names to value of expressions?
- To reuse names instead of values
- make code easier to read and modify(往往你的程序的变量名越多,那么编写可读写的代码将会容易的多)
- choose variable names wisely
- code needs to read
- 你的代码需要反反复复的观看(包括你自己和别人)
- You’ll be fine if you stick to letters, underscores(强调), don’t start with a number
- 适当地加入注释行,在 python 语言里,注释符一般使用
#。(comments start with a#)。 - 通常,我们一次给一大块的代码加注释,而不是逐行加注释
Here’s an example of a nice program:
#Compute approximate value for pi
pi = 355/113
radius = 2.2
area = pi*(radius**2)
circumference = pi*(radius*2)
再次提醒,An assignment:expression on right; variable name on left
变量不建议用单个字母,如下面的例子:
p = 355/113
r = 2.2
#multiply p with r squared
a = p*(r**2)
#multiply p with r times 2
c = p*(r*2)
1.19 Change bindings
- Once we create an object and bind it to a variable, we can change the bindings.
- 我们可以将变量名绑定到完全不同的值上!这一个特性当我们在程序引入 控制流(control flow) 的时候,将会十分有用。
- Can re-bind variable names using new assignment statements
to rebind a variable (重新绑定变量), what that means is we’re going to take the name (获取名称), we’re going to lose the binding to the previous value (失去先前绑定), and we’re going to rebind it to a new value.
- Previous value may still stored in memory but lost the handle for it
- Value for area does not change until you tell the computer to do the calculation again(意思就是,如果原先表达式的值已经求出来了并且绑定为某个变量名为a,而表达式的变量在后面发生了改变,只要不重新计算a,后续a仍然是变量没有变时计算出来的结果。下面我们看一个例子,参考讲义
mit6_100l_f22_lec01.pdf的 p.52 图,其中云朵代表内存的存放,线条代表binding)
pi = 3.14 # pi与在内存里的3.14进行了绑定
radius = 2.2 # 上同
area = pi*(radius**2) # 在内存里,它并不存储表达式,而是存储的计算结果的值,然后将其绑定到名称 area
radius = radius+1 # 在数学上,这似乎是0=1,但在 cs 上是行得通的。这里仍然先看右边,这里原先的 radius 在内存中有绑定赋值,直接算出来并接着存储到内存中,随后将左侧的变量名与之绑定。
值得一提的是,上面原先 radius = 2.2 的值,在 radius 赋值为 3.2 之后,2.2 则可能静静地放在内存中,然后等待垃圾收集回收(garbage collection)。
并且这时候,如果不对 area 发起重新计算,则 area 的值不变,仍然对应 pi*(2.2*2) 的值,而不是 pi*(3.2*2)。It just following, dumb, line by line!如果我们希望能改变,则需要重新复制 area = pi*(radius**2) ,发送指令重新计算。
Big Idea
Lines are evaluated one after the other. No skipping around, yet. No repeating. We’ll see how lines can be skipped/repeated later.(后面我们将知道如何跳过或重复行,但现在我们仅需要知道这里都是 line by line 的)
Let’s use PythonTutor to figure out what is going on.(可以让你逐步执行代码,逐行查看变量的值,更好的了解 python 发生了什么) Follow along with this Python Tutor LINK:https://pythontutor.com/visualize.html#mode=display
ex_1.5 写一个交换x和y值的程序
Swap values of x and y without binding the numbers directly. Debug (aka fix) this code.(下面这个程序为什么会报错?如何解决?)
>>> x=1
>>> y=2
>>> y=x
>>> x=y
>>> print(x)
1
根据 line by line,不难理解,一开锁当 y=x 的时候赋值到了1,但由于 y 的改变(y实际上与2失去了绑定),导致后续 x=y 的值也回到了1,无法完成我们的目的就是x和y的值进行交换。
这个过程具体可以参考讲义 mit6_100l_f22_lec01.pdf 的 p.55 图,其中云朵代表内存的存放,线条代表 binding。

解决方案:创建一个第三方的值,这里用 temp (意思是 temporary),并赋值为 y,此后当 y 进行更变为 X 的时候,temp 由于已经赋值,故无所谓 y 的更改,这时候再将 x 赋值为 temp 即可完成更换。

>>> x=1
>>> y=2
>>> temp=y
>>> y=x
>>> x=temp
>>> print(x,y)
2 1
1.20 Summary
Objects
- Objects in memory have types.
- Types tell Python what operations you can do with the objects.
- Expressions evaluate to one value and involve objects and operations.
- Variables bind names to objects. (值或对象可以存储在变量中,从而方便我们后面以更好记的名字访问)
=sign is an assignment, for ex.var = type(5*4)
Programs
- Programs only do what you tell them to do.
- Lines of code are executed in order.
- Good variable names and comments help you read code later.
Lecture 2: Strings, Input/Output, and Branching
这一次的讲座我们将围绕三个不同的主题:
- 关注一种新的 object type:string(字符串)
- 如何编写程序,获取用户输入并显示输出
- 最后我们将介绍如何编写更有趣的程序:这些程序将根据我们在代码中输入的内容作出决定。
2.1 Strings
只要是被引号(单引号、双引号都行)包裹起来的内容,就被称为字符串字面量 (String Literal)。
2.1.1 new object type: strings
- Think of a
stras a sequence of case-sensitive characters(字符串实际上是大小写敏感的字符序列)- Letters, special characters, spaces, digits…
- the characters can be anything: lower case letters / uppercase letters / the numbers on your keyboard / the special characters you see on the keyboard (甚至包含回车键
enter换行或者用tab,这些都与特殊字符有关系)
- Enclose in quotation marks or single quotes. python 创建一个字符串类型的对象的方式就是用引号将这些字符包围起来:
- 即可以是双引号
",也可以是单引号' - 我们一般会给这些字符串一个句柄(a handle)。Just be consistent about the quotes:
- 即可以是双引号
a = "me"
z = 'you'
- 我们可以对这些字符进行拼接或者重复字符串:Concatenate and repeat strings
之前我们在 tcl 语言中学过
concat命令,实际上这里也承担了一样的作用。concatenate,在英文编程术语中是“拼接、连接、串联”的意思。 - concatenate –> 用
+ - repeat –> 用
*,需要注意的是 star operator 至少有一方必须为数字
>>>a = "me" # 在内存中 a 与 "me" binding
>>>b = "myself"
>>>c = a+b # 加号可以用来进行 concatenating,形成 new object
>>>print(c)
memyself
>>> d =a+" "+b # 这里我们引入了一个有空格的特殊字符的字符串
>>> print(d)
me myself
>>> silly=a*3
>>> print(silly)
mememe
ex_2.1.1_1 What’s the value of s1 and s2?
小贴士:你可以一次复制多行进入 conda 沙盒中,但别忘记回车
# section 1
b = ":"
c = ")"
s1 = b + 2*c # 应该返回:))
# section 2
>>> f = "a"
... g = " b"
... h = "3" # 注意,这里是数字3,而不是字符串3
... s2 = (f+g)*int(h)
... print(s2)
...
a ba ba b
# section 2 error
>>> s2 = (f+g)*h
Traceback (most recent call last):
File "<python-input-14>", line 1, in <module>
s2 = (f+g)*h
~~~~~^~
TypeError: can't multiply sequence by non-int of type 'str'
# 不能用 非整数 来乘以序列!
在 ex_2.1 section 2 中,有个需要注意的细节就是 h = "3",这里 h 在内存里是 string,而不是数字,因此需要用 int() 来进行转换为整数。这里体现了 star operator 的特点,也用到了前面 第 1.12 小节 的知识点。
然而,需要注意的是,int 在转换字符串 str 的时候也有一定的要求。有些字符串如果内容原先是整数的(我们仅仅谈论字符串文本内容,暂且不论对象类型),可以正常隐式转换。然而,当字符串里的文本内容是浮点数的,这时候进行整数的 casting 会报错:
>>> int("3.9")
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
int("3.9")
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.9'
2.1.2 String operations
There’s some different things we can do with strings.
len 即为 length。我们可以获得字符串的长度。
len()is a function used to retrieve the length of a string in the parentheses. (这个函数可以告诉我们一个字符串中有多少个字符)
>>> s = "abc"
... len(s) # evaluates to 3
... chars = len(s) # len(s) is an expression that evaluates to 3
... print(chars)
...
3
2.1.3 Slicing to get one character in a string
s 即为 slicing(切片)。我们可以对字符串执行的另一件事情,那就是抓取不同位置的单个字符,往往称之为 slicing。(当然你并非一定要写 s[],也可以写 xxx[],这取决于你要切片的字符串绑定的变量名叫什么)。
- 新的 python 的表达式:Square brackets
[]used to perform indexing into a string to get the value at a certain index/position. (这个用途类似于我们在 tcl 语言中学过的lindex,不过在 python 中的实现方式是中括号)
拓展与补充:下标运算符、语法糖、s[] vs range()
下标:下标访问、下标取值、下标表达式与下标运算符
s[]的学术名称一般叫:subscription(下标访问 / 下标取值)。或者更具体地说,叫 subscript expression(下标表达式)。采用的是 subscript operator(下标运算符),也就是方括号[]这套语法。而非像
len()、range()这样的函数调用。函数调用的格式是function_name(arguments),也就是()这套语法。方括号
[]是 Python 的 subscript operator(下标运算符),用于对一个对象进行下标访问。
下面我们将从底层上来说为什么 "str"[] 可行(例如 "abc"[0] 可行),但 int[] (例如 123[]) 不可行。
- 这是由于它的形式是
对象[下标],其 CPython 的底层对象类型是字符串。更准确地说,它会走 Python 的 object protocol(对象协议),查找该对象类型是否支持下标访问。
例如,对于s = 'abc' \n s[0],其中 s[0] 在底层大致等价于:s.__getitem__(0)
再例如s[1:3],在底层则等价于 s.__getitem__(slice(1, 3, None))。
- 因此,
s[]在源代码层面、语法层面上来说不是函数调用。它的形式是对象[下标],是 Python 语言语法中的下标访问语法。
不过从更底层的角度来说,s[] 在执行的时候触发了一种特殊的回调,下面我们将介绍。
语法糖(syntactic sugar)
编程语言中为了方便程序员使用而设计的简化语法,其提供了一种更简洁、更好读的写法。
它不会增加语言本质上的新能力,只是让某些操作写起来更方便。 同时也能提供高级别抽象,隐藏底层复杂性,使代码更易于修改和维护。 例如a = a+b等价于a += b,这类更方便的表层写法都可以称为语法糖
对象[下标]中的[]是一种语法糖 syntactic sugar,背后触发的是对象的__getitem__方法。
Python 数据模型层面会调用 __getitem__,虽然语法上不是函数调用,但 Python 会把它解释成一种特殊方法调用。
例如 s[1:3] 的 1:3 会先被 Python 构造成一个 slice 对象,slice(1, 3, None)。
更底层来说,CPython 更底层:不是普通 Python 函数调用,而是协议分派。如果从 CPython 解释器更底层看,s[0] 会经过类似这样的流程:
s[0]
↓
执行下标访问字节码
↓
调用 PyObject_GetItem(s, 0)
↓
找到 str 类型实现的下标访问逻辑
↓
返回对应字符
也就是说,解释器不会真的简单粗暴地把你的代码改写成:s.__getitem__(0),然后像普通 Python 函数一样执行。
更准确地说,它会走 Python 的 object protocol(对象协议),查找该对象类型是否支持下标访问。因此,对于整数 int 来说,它不支持。因此会报错:会报错 TypeError: 'int' object is not subscriptable。这里的 subscriptable 就是 “可以被下标访问” 的意思。
s[] vs range()
关于 range() 的介绍,我们将在 第 3.3.5 小节 引用这段内容。
range()和字符串切片不一样的是,切片可以省略某个位置:例如s[::1]或s[:2]或s[:2:1]。range()是函数调用(function call),函数参数不能这样“留空”。函数调用的格式是function_name(arguments),也就是()这套语法。因此range(, 2, 1)是不合规的!- 要检验结果的话,
print(s[])是可以的,但print(range())却不能得到我们想要的结果,只能通过list(range())来检验序列抽取到列表中的元素。下面我们将着重介绍这一点是为什么,并解释为什么for循环中可以直接抓取range()映射的range object:
总的来说:
s[]是 下标表达式,它会触发字符串对象的下标访问逻辑,直接返回切片得到的新字符串对象,因此立刻从原字符串中“取出结果”;range()是 函数调用,它返回的是一个range object,这个对象本身保存的是“生成整数序列的规则”,而不是一个已经展开好的list。
由于这个非函数回调的特性,即下标运算符的特性,因此它会触发字符串对象的下标访问逻辑,并直接返回切片得到的新字符串对象。立刻从原字符串中“取出结果”,故可以直接被打印出来的:
>>> s = "012"
>>> print(s[0::])
012
而在 python 的源代码层面上的 syntax 类似的 range(),则没法通过 print() 被直接打印。
例如:
>>> list(range(0,3,1))
[0, 1, 2]
>>> print(range(0,3,1))
range(0, 3)
>>> print(list(range(0,3,1)))
[0, 1, 2]
因为 range(0,3,1) 本身不是一个普通的 list,而是一个 range object(范围对象)。print(range(0,3,1)) 打印的是这个对象本身的“描述”,即只会打印 range(0,3,1),而不是把里面的每一个数字都展开打印出来。
range()生成的是 range object 。经检查对象类型可知:
type(range(-1, 1))
<class 'range'>
- range object 并不会立刻把所有整数展开成 list,而是保存一套生成整数序列的规则:start、stop、step。
- 也就是说,
range(-1, 1)并没有直接生成[-1, 0],而是生成了 range object,其保存的是一个“规则对象”:从 -1 开始,到 1 之前停止,每次 +1。
所以 print() 打印这个 range() 对象时,打印的是它的range object 本身的对象表示:range(-1, 1)。
如果想看到规则生成出来的具体整数序列,需要强制展开:print(list(range(-1, 1, 1)))。
那为什么
list(range(-1, 1))可以看到[-1, 0]?
- 因为
list()会把 range 对象里面的值一个个取出来,然后放进一个 list 里。
为什么
for循环可以直接用range()?
- 因为
for不需要range先变成list。for会自动从range对象中一个一个取值。事实上你也可以写成for n in list(range(-1, 1)):,但没必要!
为什么 Python 要这样设计
range()?
- 因为这样更省内存。
- 比如:
range(1000000000),如果 Python 真的立刻创建一个包含十亿个整数的 list,会非常占内存。但range(1000000000)只是保存三个信息:- start = 0
- stop = 1000000000
- step = 1
- 显然,只是记住规则,而不是一次性生成所有数字,将会更节省内存。
- 我们对字符串进行编号的时候,往往称这些编号为“索引(index)”
- 有正索引和负索引,但最后一个元素一定是这两种索引方式里实际数值最大的元素
- 抓取最后一个元素常用的办法就是
s[len(s)-1](假设这个字符串存储的句柄名为s) - 中括号里既可以放数值,也可以放能求出值的表达式等其他的 pattern
Note: 对于 indexing 而言,0-based 括号里是从0开始计数的!如果你对负索引的记忆感到困惑,可以结合坐标轴的表示来理解,例如:
-3 -2 -1 0 1 2那么从左到右计数的编号就是正索引(0开始出发,0的右侧);从右到左计数的编号就是负索引(从-1开始,0的左侧)
>>> s = "abc"
# index: 0 1 2 <- indexing always starts at 0. 从左到右
# index: -3 -2 -1 <- 负索引,坐标上从右到左编号,但最后一个元素仍旧为 s[len(s)-1]
# 但对于负索引,我们习惯上还是从左到右来 ·抓取元素·(这也符合数值从小到大的顺序,保持一致性 consistency)。因此,·抓取最后一个位置的元素· 则仍旧是 ·最右侧的字符·(在本例就是索引为-1的字符c)。
>>> s[0] # evaluates to "a"
'a' # 得到的返回值
>>> s[1] # evaluates to "b"
>>> s[2] # evaluates to "c"
>>> s[3] # trying to index out of bounds, this is an error!
Traceback (most recent call last):
File "<python-input-25>", line 1, in <module>
s[3]
~^^^
IndexError: string index out of range
# 甚至可以用 negative indices 负索引
>>> s[-1] # evaluates to "c"
'c'
>>> s[-2] # evaluates to "b"
>>> s[-3] # evaluates to "a"
>>> s[-4] # this is an error.
Traceback (most recent call last):
File "<python-input-24>", line 1, in <module>
s[-4]
~^^^^
IndexError: string index out of range
# tips: 直接抓取最后一个元素的方法
>>> s[len(s)-1]
'c'
常见的一种错误:index error 索引错误。尤其是当我们开始处理更为复杂的程序的时候,更会经常遇到。这一般代表 “you’ve indexed too far into the list, either to the right or to the left.”
上述的 s[0] 不一定非要写作 s。事实上你可以任意取名并抓取字符:
>>> abc = "yuanshen"
>>> abc[1]
'u'
2.1.4 Slicing to get a substring
获取子字符串相比于获取单个字符可能会更常用。Instead of getting single characters, we could ask Python to get us a substrings. 你可以跳过某些字符,或者获取在这范围里所有的字符,又或者是使用其他的 pattern
- Can slice strings using
[start:stop:step],具体来说是string[star index:stop index:](这一点十分类似于我们在 vmd 里遇到过的帧数播放的选择语句,frame1:frame2:step) - Get characters at
startup to and includingstop-1taking everystepcharacters, but not including the stop index!
需要注意的是,我们将从开始索引
start获取每一个字符,一直到停止索引stop,但并不包括停止索引,整个范围实际上是start到stop-1。但往往我们希望覆盖到最后一个元素(最后一个元素是len(s)-1),则: 法1: 直接最后一个元素的基础上加1,即停止索引写为len(s)即可以包括最后一个元素了。 法2: 直接省略数字,只留下冒号
法1: 用 len()
>>> abc = "yuanshen"
>>> abc[4:len(abc)]
'shen'
法2: 只留下冒号
>>> s = "abc"
>>> s[1:]
'bc'
>>> s[:]
'abc'
- If give two numbers,
[start:stop],step=1by default.- 如果你总是想要获取每个字符,那么常见的做法就是省略步长部分
- If give one number, you are back to indexing for the character at one location (见第 2.1.3 节)
- You can also omit numbers and leave just colons (忽略数字只留冒号,见上面那例子,只留冒号而不写数字的时候,一律默认从头或尾,步长1。例如
s[:3]则默认从最开始,步长为1;s[0:]则默认到最后、且一定包含最后一个元素,步长为1;s[:]则默认从头到尾,步长为1)
2.1.5 Slicing example
无论是写入时的编号顺序,还是步长的正负号,都可以用如下判据进行判断:
- +ve means go left-to-right
- -ve means go right-to-left
s = "abcdefgh"
# + index: 0 1 2 3 4 5 6 7
# - index: -8 -7 -6 -5 -4 -3 -2 -1
s[3:6] # 应该是 3、4、5,即 "def",这个结果同 s[3:6:1]
s[3:6:2] # 应该是 3、5,即 "df"
s[:] # 默认从头到尾,因此是 "abcdefgh", same as s[0:len(s):1]
s[::-1] # 默认从头到尾,由于步长为负,因此方向是从右到左,因此是 "hgfedcba"
s[4:1:-2] # 应该是 4、2,即 "ec"
ex_2.1.5_1
尝试预测下面的结果:
s = "ABC d3f ghi"
# 由于string包含空格,因此上面的编号应该为:
# + index: 012 3 456 7 8910
# - index: -11-10-9 -8 -7-6-5 -4 -3-2-1
s[3:len(s)-1] # len(s)应该为11,因此应该是从3到9,默认步长为1,正向,输出应为 " d3f gh"
s[4:0:-1] # 步长-1为从右到左,但编号又要按照正向的从左到右来标,因此应该为 4321,"d CB"
# 当 start 到 end 的方向与根据 step 所指示的方向的索引编号相反时,Python 返回空字符串
s[6:3] # 这个比较特殊,从索引6到索引3,由于步长是正向,索引6在索引3的后面,所以方向是反的。Python 默认不反向切,直接返回 empty string。
# 而且这个并不报错,这是因为 f 和 f 后面没有字符满足条件了,因此返回空字符串 ''
你一定会好奇,如果是编号10,那么 s[10] 是否也可以正确的输出?答案是会的。
具体结果如下(注意空格!):
>>> s = "ABC d3f ghi"
>>> len(s)
11
>>> s[3:len(s)-1]
' d3f gh'
>>> s[4:0:-1] # 负步长决定了方向!因此实际上4到0本质上与负步长的方向一致,数字的递归方向也一致,因此不会返回空串
'd CB'
>>> s[6:3] # 默认正步长1
''
总结:当 start > end(根据 step 所指示的方向的索引编号) 时,Python 默认不反向切,故返回空字符串。
下面再考察一下容易犯错的两个例子:
s = "ABC d3f ghi"
s[8:len(s):3] # 回忆:len(s-1)是最后一个元素(因为0-based),因此可以收录至末尾
# 应当返回:' h'
s[2::-1] # 这个例子十分易错,因为-1决定了最后结尾的方向。
# 因此这里不是2:10,而是负方向2到末尾(即2到0且含0,也即-9到-11,包含-11)
# 应当返回: 'CBA'
2.1.6 Immutable strings
- 在 python 中,字符串是不可变的(immutable)。一旦创建了字符串,就无法修改它的内容。任何试图修改字符串的操作都会引发
TypeError - Strings are “immutable” – cannot be modified
- Solution:You can create new objects that are versions of the original one (创建新的 object,更改 binding 关系)
- Variable name can only be bound to one object (一个映射至另一个)
了解:为什么字符串设计成不可变的?
- 性能优化:字符串可以在多个地方共享引用而无需担心被修改
- 安全性:防止意外修改数据
- 线程安全:不需要加锁就能在多线程间共享
- python 和 tcl 语言一样,字符串不可更改。这与某些语言(如 C)不同,在C语言中你可以直接修改字符串中的字符,灵活但也危险。C语言能修改字符串恰恰是不安全的原因:缓冲区溢出正是由于可以直接修改内存导致的。Python禁止修改字符串正是为了避免这类问题而在 Rust 中则提供了两种方案,
String(可增长字符串)是可变的,&str(字符串字面量)是不可变的
>>> s = "car"
# 下面这个例子会给出错误,原因与前面我们在 ex_1.4 中讲述的有点相关。
# 这是因为 Python 中的 字符串是不可变的(immutable)。在 Python 中,一旦创建了字符串,就无法修改它的内容。任何试图修改字符串的操作都会引发 TypeError
>>> s[0] = "b" # gives an error
Traceback (most recent call last):
File "<python-input-45>", line 1, in <module>
s[0] = "b"
~^^^
TypeError: 'str' object does not support item assignment
>>> s[0] = 'b' # gives an error
Traceback (most recent call last):
File "<python-input-46>", line 1, in <module>
s[0] = 'b'
~^^^
TypeError: 'str' object does not support item assignment
# 如果你想修改字符串,需要在内存中创建一个新的字符串,然后更换 binding 关系
>>> s = 'b'+s[1:len(s)] # is allowed, s bound to new object
>>> print(s)
bar
# 更简洁的写法:
>>> s = 'b'+s[1:]
>>> print(s)
bar
# 同之前所述的那样,先算右边的方程,然后放入内存,最后再赋值给左侧
# 而 car 则仍然还在内存中,只是 losing the binding
拓展:其他不可变和可变的对象
| 类型 | 英文名称 | 是否可变 | 简要说明 |
|---|---|---|---|
int | integer | 不可变 immutable | 整数对象本身不能被修改,变量变化通常是重新绑定 |
float | floating-point number | 不可变 immutable | 浮点数对象本身不能被修改 |
bool | Boolean | 不可变 immutable | True 和 False 是不可变对象 |
str | string | 不可变 immutable | 字符串内容不能原地修改 |
tuple | tuple | 不可变 immutable | 元组本身不能增删改元素 |
list | list | 可变 mutable | 可以原地添加、删除、修改元素 |
dict | dictionary | 可变 mutable | 可以原地添加、删除、修改键值对 |
set | set | 可变 mutable | 可以原地添加、删除元素 |
Big idea
If you are wondering “what happens if”… Just try it out in the console!
2.2 Input/Output
到目前为至,我们能写到程序是相对静态的(pretty stagnant),尤其少了与用户的互动,这一小节我们将来介绍这些概念。
2.2.1 Printing
- Used to output stuff to console 用于将内容输出到控制台
# 下面这个格式是在 anaconda 中的形式,这得到的并不是“真正的输出”
In [11]: 3+2
Out[11]: 5
“Out” tells you it’s an interaction within the shell only. 教授认为,这是一种 peeking into the value of the expression (窥视表达式的值),若真正用 python 执行,则不会打印任何信息。
Output using the print statement.
- Command is
print
In [12]: print(3+2)
5
No “Out” means it is actually shown to a user, apparent when you edit/run files.
- Printing many objects in the same command
- Separate objects using commas
,to output them separated by spaces 逗号代表插入空格,输出的结果将会带有空格间隔 - Concatenate strings together using
+to print as single object
- Separate objects using commas
a = "the"
b = 3
c = "musketeers"
# separate objects: commas`,`
>>> print(a, b, c)
the 3 musketeers
# 事实上,也可以写成:
>>> print(a,b,c)
the 3 musketeers
# 注意上述表述的空格是针对输出结果的,而非一定要print括号里逗号后就一定要紧跟着空格
# concatenate string: plus `+`
# 如果因某种原因不需要空格,写成下面的表达会报错:
>>> print(a + b +c)
Traceback (most recent call last):
File "<python-input-11>", line 1, in <module>
print(a + b +c)
~~^~~
TypeError: can only concatenate str (not "int") to str
# 这里需要将 b(因为原来是 int 型)转换为 string (即 str 型),只有字符串才能和字符串进行 concatenating
>>> print(a+str(b)+c)
the3musketeers
# 同理,下面这个表述也是允许的:
>>> print(a + str(b) +c)
the3musketeers
Note: Every piece being concatenated must be a string!
2.2.2 Input
下面我们将观察这个等式,从 user 的角度和开发者的角度来看待这里面是发生了什么事情:
x = input(s)
Prints the value of the string
s- 标准输出(Standard Output, stdout)与 提示符 Prompt:python 调用
input()这个函数,首先会将参数s(通常称为 Prompt)输出到 user 的终端屏幕上。
- 标准输出(Standard Output, stdout)与 提示符 Prompt:python 调用
- 例如,
s为"password:",则 console 中会变成这样的界面:password: # And it waits for characters and Enter to be hit
User types in something and hits enter
- 对于用户而非开发者而言,则要求进一步输入字符和回车
- 线程阻塞(Blocking)与标准输入(Standard Input, stdin):打印完
s之后,程序并没有继续往下走,而是进入了阻塞 (Blocking) 状态。这一点相当于 tcl 语言中的gets stdin。
- 线程阻塞(Blocking)与标准输入(Standard Input, stdin):打印完
- 此时 Python 解释器在监听你的键盘输入流 (stdin),它在“挂起”等待一个特定的触发信号——即你按下回车键
Enter(产生一个换行符\n)。 - 返回值 (Return Value) 与 内存创建:按下回车后,
input()函数的使命就完成了。它会将 user 敲击的所有字符(不包括最后的换行符\n)打包成一个字符串对象 (String Object),作为这个函数的返回值 (Return Value)。
- 返回值 (Return Value) 与 内存创建:按下回车后,
That value is assigned to the variable
x- 变量绑定 (Variable Binding): Python 会把 user 刚刚输入的内容打包成字符串对象放在内存里,然后把该返回值赋值绑定给
x这个变量上。一定要注意,当x绑定的是input()函数的值时,最终等式右侧的输入会替换为用户输入的字符串版本,那么x一定绑定的是 str 类型的对象!
- 变量绑定 (Variable Binding): Python 会把 user 刚刚输入的内容打包成字符串对象放在内存里,然后把该返回值赋值绑定给
Binds that value to a variable [这里可以参考讲义 lecture 2 pp.17-pp.19]
text = input("Type anything:")
print(5*text) # 因为 input 一定得到 string,因此 text 一定是 string,故可以 replicate
# 用户看到的 shell 应该提示:
Type anything:
# 用户输入 howdy,并回车
Type anything:howdy
[Enter]
# 此时内存创建了 "howdy" 的字符串对象,随后 text 进行了 binding,因此 text 赋值为 "howdy",并执行 print(5*text)
# 因此用户应该看到的结果是:
Type anything:howdy
howdyhowdyhowdyhowdyhowdy
Note: 几点注意
input()函数不管你输入的是什么,它的返回值永远是一个字符串 (Str 类型)。 因此,假设password:为123,那么 user 输入之后,x绑定的不是 int 类型的123,而是 str 类型的'123'。input()括号里不一定非得是字符串类型,但若填入 标识符(Identifier / 变量名),其允不允许,完全取决于上下文。 例如:(a)input("password:")一定是对的,只要是被引号(单引号、双引号都行)包裹起来的内容,就被称为字符串字面量 (String Literal)。明确的文本数据直接可以打印在屏幕上。 (b)input(password)是否能运行,则取决于上下文。当没有引号时,Python 解释器会把它当作一个 标识符 (Identifier),也就是我们常说的变量名。 如果内存中不存在这样的password变量,则直接报错NameError。 如果先前已经赋值该变量为一个字符串,例如password = "您的密码:",则这里的input(password)可以正常运行。【注意,这里 password 绑定的是一个字符串类型的对象】 (c)如果变量绑定的对象不是 str 类型的呢? 事实上,在 Python 中,input()函数的底层设计非常包容。如果你传进去的变量不是字符串,也可能不会报错,而是会默默地做一次隐式类型转换(Implicit Type Conversion)。 例如,先前已经定义error_code = 404,当直接调用user_input = input(error_code)的时候,Python 的解释器在底层会自动调用str(404),把 int 类型的404临时转换成 str 类型的 “404”,然后打印在终端屏幕上作为提示符。
inputalways returns an str, must cast if working with numbers
所以,对于需要用户输入年龄的类型,而后续我们又需要用变量 x 去进行加减计算的时候,则需要对 sclar object 标量对象的类型进行转换 type casting。
ex_2.2.2_1 input() 常见的类型错误
x = input("请输入年龄:")
# 若用户输入18,此时 x 实际上绑定的是字符串 '18'
# 若程序下一步指令为:
明年年龄 = x+1
# 直接报错:类型错误 (TypeError)
# 解决方法:显式地进行类型转换 (Type Casting)
# 如果你需要数字,你必须在获取输入后,手动把它变成整数 (int) 或浮点数 (float)。
x = int(input("请输入年龄: "))
上面这种解决方法称为 函数的嵌套调用,它会先执行里面的 input 拿到字符串,然后再通过外面的 int 把字符串加工成整数,最后绑定给 x。
ex_2.2.2_2 预测下面两个结果有何区别
# part1: no casting
num1 = input("Type a number: ")
print(5*num1) # -> 实际对应字符串的 replication,"3"
# part2:
num2 = int(input("Type a number: "))
print(5*num2) # -> 实际已经成运算,3
###### user #######
# part1
Type a number:3
33333
# part2
Type a number:3
15
ex_2.2.2_3 尝试写一个程序
Write a program that:
- Asks the user for a verb
- Prints “I can _ better than you” where you replace _ with the verb.
- Then prints the verb 5 times in a row separated by spaces.
- For example, if the user enters
run, you print:
I can run better than you!
run run run run run
- my homework:
verb = input("I can _ better than you")
print("I can"+" "+verb+" "+"better tha you")
print(verb,verb,verb,verb,verb)
# for example:
>>> verb = input("I can _ better than you")
... print("I can"+" "+verb+" "+"better than you")
... print(verb,verb,verb,verb,verb)
...
I can _ better than yourun
I can run better than you
run run run run run
- solution:
question = input('Choose a verb:')
print('I can',question,'better than you')
# or:
# print('I can '+question+' better than you')
print((question+' ')*5) # solution 1
# solution 1回车的时候,最后一个 run 还会再多带一个空格,因此不够符合题意
# or:
print(question,question,question,question,question) # solution 2
# or:
print((question+' ')*4+question) # solution 2
2.2.3 An important algorithm: Newton’s method
So with what we know so far, we can actually apply some of these ideas to a more numerical example.
- 牛顿法实际上是一种使用连续逼近的思想来抓取多项式的根的方法。(根据需要逼近这一点,可以猜测应该是需要用到循环语句的)
不过对于此法,以我们目前的所知并不能写完一个完整的算法,但是我们可以写出一个其中非常重要的部分,即根据初始猜测得到下一个猜测的部分。现在,你不必理解整个算法是如何来的、怎么运行的,我们只需要设计 “the next guess based on an original guess”。
应用场景:
- Finds roots of a polynomial (找一个多项式求其根)
- e.g. find g such that $f(g,x) = g^{3}-x$
- Algorithm uses successive approximation
- $next_guess = guess - \frac{f(guess)}{f^{’}(guess)}$
- Partial code of algorithm that gets input and finds next guess
ex_2.2.3_1 Newton’s method
我们将先介绍一下 hard code 硬编码版本的,然后再接着介绍一下经改动和优化后的版本。
# try: Newton's Method for cube root
x = int(input('What x to find the cube root of? :'))
g = int(input('What guess to start with? :'))
# 上面会 print “你想要解立方根的x是多少?” “初猜是多少?”,用户需键入数字进行交互
# 使用了两次 cast,这意味着我们输入得是数字
print('Current estimate cubed = ', g**3)
next_g = g - ((g**3 - x)/(3*g**2))
print('Next guess to try = ', next_g)
这个处理过程是比较简陋的,因为还得一轮轮的手动输入 nextguess。大致计算流程:
- $f(g,x) = g^{3}-x$ :先键入要解立方根的
x,并输入初猜g - 程序会打印 $g^3$
- 程序将会使用该方程 $next_guess = g - \frac{f(guess)}{f^{’}(guess)} = g - \frac{g^3-x}{3·g^2}$,代入 x 和 g,解出 next_guess
- 要进行下一轮的逼近,则需要将 next_guess 作为新的初猜代入到上式
运行的内容大概如此(讲义所给出的版本):
>>> x = int(input('What x to find the cube root of? :'))
... g = int(input('What guess to start with? :'))
...
... print('Current estimate cubed = ', g**3)
... next_g = g - ((g**3 - x)/(3*g**2))
... print('Next guess to try = ', next_g)
...
What x to find the cube root of? :27
What guess to start with? :3
Current estimate cubed = 27
Next guess to try = 3.0
显然,这段代码有许多的不足:
- 不能自动循环逼近,并自行设置一个收敛限
- 如果解出来的下一个初猜是浮点数,重新输入交互的时候,浮点数变成了字符串,而 g 是将字符串转换成整数,当字符串的文本内容实际为浮点数时则会报错(见 ex_2.1.1_1)。
# 引发报错的初猜
>>> g = int(input('What guess to start with? :'))
What guess to start with? :2.88
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
g = int(input('What guess to start with? :'))
ValueError: invalid literal for int() with base 10: '2.88'
>>> g = int(input('What guess to start with? :'))
What guess to start with? :3.0
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
g = int(input('What guess to start with? :'))
ValueError: invalid literal for int() with base 10: '3.0'
# 显然只能输入初猜为3的时候才不报错
解决办法:不使用 int() 而是使用 float() (类似于我们在 tcl 中学到过的 double())
>>> x = float(input('What x to find the cube root of? :'))
... g = float(input('What guess to start with? :'))
...
... print('Current estimate cubed = ', g**3)
... next_g = g - ((g**3 - x)/(3*g**2))
... print('Next guess to try = ', next_g)
这样后续进行下一轮输入的时候就可以愉快地输入浮点数了,具有更好的向下兼容性,从而达到我们前面强调的 type consistency。
如何完成这个循环? 这里可以提前剧透:使用 while 循环
- $f(g,x) = g^{3}-x$
- $next_{g} = g - \frac{g^{3}-x}{3·g^{2}}$
- 使用
while循环,设置收敛限,未达到则继续循环 - 利用 line by line 的机制,迭代更新 g
改进的完全版总览:
target = float(input('What target number to find the cube root of? :'))
g = float(input('What guess to start with? :'))
epsilon = 0.01 # 设置收敛限(允许的误差范围)
num_guesses = 0 # 计数器,用于记录迭代了多少次
# 只要误差的绝对值大于等于收敛限,就继续迭代
while abs(g**3 - target) >= epsilon:
print(f'Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f}')
# 利用到了 f-string,并且指定了打印出来的参数格式
# Newton 迭代的核心公式
g = g - ((g**3 - target) / (3 * g**2))
num_guesses += 1
# 打印打印迭代次数,以及在上述收敛限内的立方根
print(f'\nTotal iterations = {num_guesses}')
print(f'Estimated cube root = {g}')
下面我们将一行行来看,并且会适当结合 tcl 语言进行对比:
- 终端打印提示符,等待用户输入:
target = float(input('What target number to find the cube root of? :'))
g = float(input('What guess to start with? :'))
获取输入后,input() 隐式转换为字符串,接着被外层的 float() 显式转换 (Cast) 为浮点数,最后绑定到变量 target 和 g 上。
- 初始化两个关键变量:
epsilon = 0.01 # 设置收敛限(允许的误差范围)
num_guesses = 0 # 计数器,记录迭代了多少次
epsilon(希腊字母 $\epsilon$):在科学计算中,它通常代指一个极小的正数(因此为了符合数学直觉,后面我们写公式的时候要用到abs()函数来得到差值的绝对值,再和 $\epsilon$ 比较)。- 为什么要设置收敛限? 因为浮点数很难做到绝对的等于 0(比如 0.1 + 0.2 == 0.3 在 Python 中是 False),所以我们只能要求计算结果与目标的差值“足够小”,这个“足够小”的界限就是收敛限。
例如下面的例子,其中第二个例子鲜明地展示了浮点数相加的时候难以达到绝对的准确,因此当你指定验证是否严格为
0.3的时候,会得到False的结果:
>>> 0.1+0.2==0.3
False
>>> 0.1+0.2
0.30000000000000004
num_guesses:用来记录我们的 while 循环到底跑了多少圈,后续可以打印出迭代次数(计数器可以打印出来获得我们感兴趣的信息)
while循环的条件判断
while abs(g**3 - target) >= epsilon:
- 判断计算误差是否满足 $g^{3}-x ≧ \epsilon$,若输出为
True则未达收敛限,循环继续。 abs():Python 的内置函数,求绝对值 (Absolute value)。因为我们不知道当前的猜想是猜大了(正误差)还是猜小了(负误差),所以我们只看误差的绝对大小。
- 格式化打印当前状态(打印当前
g迭代的值为多少,并且给出)。这里还利用到了 f-string,即格式化字符串字面量 (Formatted String Literals):
print(f'Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f}')
这里有几个关键:
i. f-string 与 {}
- f-string,即格式化字符串字面量 (Formatted String Literals)
- 若仅仅只写
print('Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f}')(少了f),则仅仅是纯字符串的打印!打印结果只会为Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f},被当成纯文本处理 print()里加上f(格式化字符串 / f-string),python 解释器则会切换到“解析模式”,当扫描到字符串{}则会认定非普通文字,而是当成 Python 代码去进行计算或变量替换等等(这里它会把 g 的值替换进去)- 在 Python 的 f-string 中(也就是以字母
f开头的字符串,比如f'...'或f"..."),当双引号(python 不区分" "与' ')内含有花括号{},则就像是在字符串里开了一个“执行窗口”。 - Python 的 f-string 属于字符串插值 (String Interpolation) 技术。它只在花括号
{}划定的区域内执行表达式,目的是为了把计算结果转化为文字,拼接到长字符串中。 p.s. 这个功能实现类似于在 Tcl 中双引号内的命令替换[...]和变量替换$。而 Python 的 f-string 中的{}把这两者完美结合了。在{}里面,你可以写任何合法的 Python 表达式(变量名、数学运算、甚至是函数调用)。Python 在运行到这里时,会优先计算{}里面的内容,然后把结果变成文字,无缝拼接到外面的字符串中。
例如一个同样功能的代码,tcl 为:
set g 3
puts "Cube is [expr {$g**3}], next guess..."
而在 python 中则为:
g = 3
print(f"Cube is {g**3}, next guess...")
此外,还需要比较一下 tcl 和 python 中的内置函数eval:
# 假设这是一个纯文本字符串,可能是从文件里读出来的,或者网络接收的
math_formula = "3**2 + 4**2"
# f-string 做不到直接执行整段外部字符串
# print(f"Result: {math_formula}")
# 这只会打印出:
Result: 3**2 + 4**2
# 但 eval() 可以把它当成代码强行执行
result = eval(math_formula)
print("Result:", result) # 别忘了comma是空格!
# 这会打印出:
Result: 25
- f-string 做不到直接执行整段外部字符串
- python 中的
eval()可以把它当成代码强行执行(如果是 tcl 中的则为eval ?string?直接接上字符串)
此外,这里有张字符串插值和 eval 函数的区别小结:
Table_2.2.3_1
| 特性 | Python 的 f-string f"{...}" | Tcl / Python 的 eval |
|---|---|---|
| 核心定位 | 高级字符串拼接工具 | 动态代码执行引擎 |
| 执行范围 | 只执行事先写在花括号 {} 里的内容 | 执行传入的整个字符串 |
| 解析时机 | 在代码编译阶段就已经确定了结构 | 在代码运行阶段 (Runtime) 临时解析执行 |
| 安全性 | 绝对安全。外部输入无法注入到 {} 中执行代码 | 极度危险。如果把未经审查的字符串传给 eval,相当于向黑客敞开大门 |
综上所述,这里 print(f'Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f}') 由于 f-string,因此执行 {g:.4f} 内部的变量名和替换
ii. g:4f 是 Python 下达格式化指令 (Formatting Specification)
- 语法为
{ 表达式 : 格式化指令 } - 其中表达式它可以是单个变量:
{g :...},可以是数学运算:{g**3 :...},可以是函数调用:{abs(g**3 - target) :...}。在这个区域里,Python 会启动类似 Tcl 里面[expr ...]的引擎,算出最终的那个表达式对应的数值。 - 这个
:这个十分类似于 tcl 语言中的格式化排版中format命令的作用,说明开启格式化指令 .4f:.(Dot):表示后面要跟的是精度 (Precision) 设置;4代表小数点后精确保留 4 位数字。如果原数字精度不足,会用 0 补齐;如果超出,会进行舍入;f:代表 Fixed-point (定点浮点数)表示法,而不是科学计数法(科学计数法用 e)
- 事实上,
.4f类似于 tcl 语言中的排版格式%.4f(tcl中需要%作为格式化指令的引导符),这是由于他们都采用 C 语言标准库中的printf语法,满足 IEEE 754 浮点数格式化规范。 - 其实,Python 早期的设计也是如此:在 Python 引入 f-string(Python 3.6+)之前,Python 最古老的字符串格式化语法,长得和 Tcl / C 语言一模一样,被称为 “
%格式化操作 (Percent Formatting)”
综上所述,继上面{}划定的区域内将 g:4f 当成 python 代码执行,则 g 当表达式得到值,然后依据 :4f 格式化为保留小数点后四位。另一个打印的差值也是同理,只不过多算了 abs() 求绝对值的函数。
- 根据 line by line 的规则,进行状态更新 (State Update):
g = g - ((g**3 - target) / (3 * g**2))
这也是用到结构上的小巧思:先算右边等式,算出下一个更精确的猜想值。然后将原变量 g 重新绑定 (Re-bind) 到这个新算出来的浮点数对象上。原来的旧数值就被丢弃了。这是循环能往前推进的引擎。
num_guesses += 1每循环一次,迭代次数的计数器 +1:+=是就地加法 (In-place addition) 操作符。num_guesses += 1完全等价于num_guesses = num_guesses + 1。(相当于 Tcl 里的incr num_guesses 1)。 更通用的写法是:a = a + b等价于a += b循环结束,打印结果:
print(f'\nTotal iterations = {num_guesses}')
print(f'Estimated cube root = {g}')
循环结束(说明误差已经小于 0.01 了),打印最终结论.
这里还有个小巧思:由于有反斜杠,\n 代表一个换行符,即这个字符串到时候还会包含一个全新的空行在第一行,第二行才是 Total… 。让输出的结论和上面的循环日志空开一行,更易读。
下面我们来展示下这个代码实际运行的结果如何:
>>> target = float(input('What target number to find the cube root of? :'))
... g = float(input('What guess to start with? :'))
... epsilon = 0.01
... num_guesses = 0
... while abs(g**3 - target) >= epsilon:
... print(f'Current guess = {g:.4f}, Error = {abs(g**3 - target):.4f}')
... g = g - ((g**3 - target) / (3 * g**2))
... num_guesses += 1
... print(f'\nTotal iterations = {num_guesses}')
... print(f'Estimated cube root = {g}')
...
What target number to find the cube root of? :99
What guess to start with? :7
Current guess = 7.0000, Error = 244.0000
Current guess = 5.3401, Error = 53.2849
Current guess = 4.7173, Error = 5.9732
Current guess = 4.6278, Error = 0.1126
Total iterations = 4
Estimated cube root = 4.626065673046142
就此我们解决了 ex_2.2.3_1 这个例子,实际上如果半途遇到不收敛或发散,这时候我们就得考虑 break (我们在写 tcl 脚本中也学过很经典的 while {1} {...} 与 break 的搭配)
2.2.4 F-strings
- F-strings: formatted string literals. It’s a more convenient way for us to print out mixtures of literal text and resulting expressions.
- Available starting with Python 3.6
- Character
ffollowed by a formatted string literal (格式化字符串字面量)- Anything that can be appear in a normal string literal
- Expressions bracketed by curly braces
{}i.e., anything that’s within a curly bracket{}is considered an expression in Python
- Expressions in curly braces
{}evaluated at runtime, automatically converted to strings, and concatenated to the string preceding them
对比下面这几个表达,体会哪个更优雅和方便:
>>> num=3000
>>> fraction=1/3
>>> print(num*fraction, 'is', fraction*100, '% of', num)
1000.0 is 33.33333333333333 % of 3000
# "'is', fraction..." introduces an extra space
>>> print(num*fraction, 'is', str(fraction*100) + '% of', num)
1000.0 is 33.33333333333333% of 3000
# 有时也可以用 casting 和 concatenation,注意是字符串的拼接功能
>>> print(f'{num*fraction} is {fraction*100}% of {num}')
1000.0 is 33.33333333333333% of 3000
# 在输出到屏幕之前,python 会优先计算大括号内的表达式
# 一般在允许的情况下,优先选择使用 f-strings 往往会是个更好的选择
Big idea
- Expressions can be placed anywhere.
- Python evaluates them!
2.3 Conditions for branching
这一节我们将讨论条件分支(conditions for branching)。截至目前为止,上述的讨论写出来的程序基本都是线性的(逐行算的):a bunch of lines of code, and they get evaluated one by one。 线性的程序无法做到:
- 跳过某些部分(skip)
- 重复某些内容(repeat)
- 没有决策点(decision point),得到的值只是程序中的值
现在我们要来考察如何在程序中添加决策点。具体来说,例如某个变量值小于另一个变量值,我们想对某些代码进行评估,如果反之,我们想跳过某段代码,那么这样的过程既创造了决策点,也创造了条件分支。
2.3.1 Binding variables and values
- In CS, there are two notions of equal:
- Assignment and Equality test
小心比对下面这两种情况的区别(一个是赋值操作,一个是判别操作):
variable = value- Change the stored value of variable to value (assignment, 右边的值绑定到左边)
- Nothing for us to solve, computer just does the action
some_expression == other_expression- A test for equlity(查看等价性)
- No binding is happening
- Expressions are replaced by values and computer just does the comparison
- Replaces the entire line with
TrueorFalse(给出 boolean results) - 表达式不必仅仅是数值
2.3.2 Comparison operators
iandjare variable names- They can be of type ints, float, strings, etc.
- Comparisons below evaluate to the type Boolean
- The Boolean type only has 2 values:
TrueandFalse
- The Boolean type only has 2 values:
for instance:
i > ji >= ji < ji <= ji == j–> equality test,Trueifiis the same asji != j–> inequality test,Trueifinot the same asj- With strings, be careful about case sensitivity:
March != march
2.3.3 Logical operators on bool
事实上我们可以把它们 combine 在一起。
- 假设:
aandbare variable names (with Boolean values)not a–>TrueifaisFalseFalseifaisTrue
a and b–>Trueif both areTruea or b–>Trueif either or both areTrue
p.s. If you use the symbol & and it’s not the same as and! & 在 python 中有别的含义,它是一个和与数字相关的位操作运算符(it’s an operator with the bits of the number.)
例如:
>>> not (2<3)
False
>>> not 2<3
False
>>> (2<3) and (3<4)
True
>>> (2<3) and (3>4)
False
2.3.4 Comparison example
下面都是比较操作:(这里的内存图可以参考讲义 lecture 2 的 pp37)
>>> pset_time = 15
... sleep_time = 8
... print(sleep_time > pset_time) # 打印语句会在内存中抓取抓取相应的表达式,并进行评估得到 Boolean 值
...
False # prints the boolean False
>>> derive = True
... drink = False
... both = drink and derive
... print(both)
...
False
>>> derive = True # derive 在内存中的值为 True
... drink = False
... both = drink or derive
... print(both)
...
True # prints the boolean True
ex_2.3.4_1 写一个猜数字的程序
Write a program that
- Saves a secret number in a variable.(presumbly, people using your program won’t be looking at the program itself and, they’ll just be interacting with the program in the shell)
- Asks the user for a number guess.
- Prints a bool
FalseorTruedepending on whether the guess matches the secret.
my work:
password = 8
test = int(input("猜猜是我多少?提示是一位整数:"))
# 我认为这里有必要引入类型转换,否则后面 str 和 int 会死货对不上
print(test == password)
#####test#####
>>> password = 8
... test = int(input("猜猜是我多少?提示是一位整数:"))
... print(test == password)
...
猜猜是我多少?提示是一位整数:2
False
如果想要交互到猜出正确答案才可以进入,那么就可以考虑写成含 while 的循环:
password = 8
# 初始化一个假的初猜值,只要 ·保证它不等于· password 即可·进入循环·
test = -1 # 设定假初始值的目的是为了进入循环
# 只要猜的数字不等于密码,就一直循环
while test != password:
test = int(input("猜猜是我多少?提示是一位整数:"))
if test == password:
print("恭喜你,猜对了!True")
else:
print("猜错了,继续努力!False")
思维拓展:如果要设防避免用户从源码查看密码,该怎么做? 对于这个猜数字游戏在这种本地运行的单机小游戏中,想要完全防止用户查看源码获取答案是几乎不可能的。 因为:
- Python 是解释型语言,代码必须以某种形式存在才能运行
- 用户在自己的电脑上运行程序,拥有完全的访问权限
不过这只是个练习程序,重点是学习编程逻辑,而不是真正的安全防护。注意下面的循环的书写中,缩进 indentation 对 python 来说很敏感!这点和 tcl 语言十分不同!
- 单向哈希加密 (Cryptographic Hashing)
如果你必须把密码写在代码里,但又不想让人看懂,你就需要用到密码学中的哈希函数 (Hash Function)。简单来说就是将导入的数值通过 SHA-256 处理为哈希值,其他人基本上无法延续刚刚的路线生成该哈希值,因此,这个过程是单向的(不可逆)。因此,我们可以在代码里只存哈希值,不存明文。
代码实现我们可以使用 Python 内置的
hashlib。
import hashlib
# 存储密码的哈希值而不是明文
password_hash = hashlib.sha256(b'8').hexdigest()
# 例如生成的 password_hash = "2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881"
while True:
test = input("猜猜是我多少?提示是一位整数:")
# 注意这里先不转 int,因为我们需要把用户输入的字符串直接扔进 SHA-256
test_hash = hashlib.sha256(test.encode('utf-8')).hexdigest()
if test_hash == password_hash:
print("恭喜你,猜对了!True")
break
else:
print("猜错了,继续努力!False")
- 适用场景:真实的密码验证系统(如网站登录)
- 局限性:对于 0-9 这种小范围数字,别人可以轻易暴力破解(计算 10 个数字的哈希值对比即可)
- 环境变量 (Environment Variables) —— “把秘密藏在系统里”
这是最推荐、最标准、也是人们在配置科学计算软件(如 PySCF 或 GaussiMY_SECRET_NUMBERan)时最常用的方法。核心思想就是代码里根本就不写密码,代码只负责向操作系统去要密码。
操作步骤如下: (1) 在zsh 终端里(bash 也行),悄悄设置一个环境变量:
export =8
(2) 在 python 代码里使用 os 模块去读取它:
import os
# os.getenv 会去你的 Linux/macOS 系统里找名为 'MY_SECRET_NUMBER' 的变量
# 如果找不到,为了防止报错,我们给它一个默认值 None
# 注意:环境变量读进来默认是字符串,所以需要用 int() 转换
password = int(os.getenv('MY_SECRET_NUMBER', 0))
test = int(input("猜猜是我多少?提示是一位整数:"))
print(test == password)
- 适用场景:配置管理、API 密钥存储
- 局限性:用户仍然可以通过
echo $MY_SECRET_NUMBER查看
- 编译成字节码,代码混淆与打包 (Obfuscation & Freezing)
如果想把整个 .py 源码藏起来,不想让别人看到任何逻辑。可以把 Python 脚本“打包”成一个直接可以双击运行的独立程序(在 macOS 上是 .app,在 Linux 上是 ELF 可执行二进制文件)。
- 常见的打包工具就是
PyInstaller,不过要确保pip install pyinstaller。 在终端里运行(需要先pip install pyinstaller):
pyinstaller --onefile your_program.py
- 或者是编译 Python 文件:
python -m py_compile your_program.py
# 生成 __pycache__/your_program.cpython-*.pyc
上述两种操作会生成一个二进制文件。别人只能运行它,双击打开看到的是一堆无法阅读的机器码(乱码)。这种方法在计算机科学里被称为“混淆 (Obfuscation)”,而不是“加密 (Encryption)”。
- 适用场景:分发商业软件
- 局限性:Python 字节码可以被反编译,只是增加了一点难度。可以使用反汇编工具(如 IDA Pro)把这个二进制文件重新“反编译”回 Python 代码。
如果想让游戏更有趣,还可以考虑:
- 随机生成密码:
import random; password = random.randint(1, 9) - 添加猜测次数限制
- 给出"太大了"或"太小了"的提示
2.3.5 Why bool?
- When we get to flow of control, i.e. branching to different expressions based on values, we need a way of knowing if a condition is true
- E.g., if something is true (Boolean), do this (some commands), otherwise do that (some other commands)
2.3.6 Branching in Python
下面我们将分几种情况来介绍。不过万变不离其宗,其基本上都有如下两点特质:
<condition>has a valueTrueorFalse- Indentation matters in Python! (别的语言可能会对前面的缩进长度不敏感,但 python 对缩进这一点十分地敏感!)
- 缩进错误十分常见,一定要谨慎谨慎再谨慎!一般是四个空格的缩进为一个谓词控制的 block。
- 如果说当你
<condition>表达式较长时,为了便于阅读,你可以加上小括号(),例如if (A > B)和if A > B与if A>B都是被允许的。
Case 1:
if <condition>:
<code>
<code>
...
<rest of program>
- Do code within
ifblock(if区块下的这几行) when condition isTrue.
Case 2:
if <condition>:
<code>
<code>
...
else:
<code>
<code>
...
<rest of program>
- Do code within
ifblock when condition isTrueor code withinelseblock when condition isFalse.(这里形成决策点上的分支,如果if的条件是 True 就执行,否则执行else模块的) - 因此,上述代码有可能没有任何条件成立,那么将跳过上述所有代码的 body 部分
elseblock:- 不用带条件
<condition> - 只能出现0次或1次
- 必须是整个结构的最后一部分
- 执行的 timing 是前面所有条件都为
False
- 不用带条件
jimmy 总结:else 是非黑即白的,当所有可能都不成立时的最终处理
Case 3: (体会好 else 与 elif 的区别)
if <condition>:
<code>
<code>
...
elif <condition>:
<code>
<code>
...
elif <condition>:
<code>
<code>
...
<rest of program>
- Run the first block whose corresponding
<condition>isTrue elif=else+if,中文里常译为多条件判断,即如果不满足上一个判断条件,那么就在elif语句下继续进行判断elifblock:- 需要带
<condition> - 出现次数可以是0次、1次或多次
- 出现的位置必须紧跟
if或另一个elif之后 - 执行实际需为自己 block 之前的条件都为
False且轮到自身时,自己的 block 条件为True
- 需要带
jimmy 总结:需要再判断另一种可能性时用 elif。
Case 4: comprehensive
if <condition>:
<code>
<code>
...
elif <condition>:
<code>
<code>
...
else:
<code>
<code>
...
<rest of program>
Run the first block whose corresponding
<condition>isTrue. Theelseblock runs when no conditions wereTrue.此外,
if只执行boolean为True的代码块,像False,None,数字0、0.0,空字符串"",空容器[]、{}、()这些在if中均被当作假,语法没错但不执行相应的代码。
2.3.7 Branching example
# 下面是一个时间计划的计算,一天的时间是24h
pset_time = 22
sleep_time = 8
if (pset_time + sleep_time) > 24:
# 上述一行中的 <condition> 会被评估为 Boolean
print("impossible!") # this indented code executed if line above is True
elif (pset_time + sleep_time) >= 24:
print("full schedule!") # this indented code executed if line above is True and the if condition is False
else:
leftover = abs(24-pset_time-sleep_time)
# 使用了 abs() 函数计算绝对值
print(leftover,"h of free time!") # this else block runs only if previous conditions were all False
print("end of day")
不难看出,上述之所以强调 indentation 就是因为 python 中对于不同 block 区分(例如上面的 if block、elif block、else block)的执着。如果不进行缩进的区分,那么我们无从分辨最后一行的 print("end of day") 到底是分支之外的段落,还是 else block 下的 body。而在别的语言可能是用 {} 来区分 block。
而且务必注意的是,上述 it’s indented by usually four space(两次 Tab 键!4个空格)
ex_2.3.7_1 判断下面的代码是否有问题
- Semantic structure matches visual structure(参考 lecture 2 讲义上 pp44,通过色块来可视化成语法的视觉结构)
- Fix this buggy code (hint, it has bad indentation)!
# Buggy, fix it!
x = int(input("Enter a number for x: "))
y = int(input("Enter a different number for y: "))
if x == y:
print(x,"is the same as",y)
print("These are equal!")
显然当x和y不相等的时候,print仍旧会打印出These are equal!。
解决方案:We rejoin the rest of a program because the indentation level of this print statement print("These are equal!") is the same as the rest of our program.(即没有缩进,与 if 同级别了)。
2.3.8 Indentation and nested branching
nest 可以作为 嵌套(信息) 的意思。nest conditionals 即嵌套条件语句。这一节我们将介绍缩进与嵌套的分支。
- Matters in Python
- How you denote blocks of code
- 一旦我们创建了条件语句,那么同缩进下的代码区域就是一个代码块。然后在该代码块内,再引入决策点即嵌套条件语句时,则又会引入隶属于该嵌套语句的缩进下的代码。而后续创造的分支都隶属于原先一开始的代码块区域。
## NESTED BRANCHING ##
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal") # 缩进四个空格
if y != 0:
print("therefore, x / y is", x/y) # 嵌套,所以缩进了八个空格
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")
Big idea
- Practice will help you build a mental model of how to trace the code.
- Indentation does a lot of the work for you!
- Python is unique in the sense because there’s no other languages that actually force you to indent things.
- 虽然会遇到段错误,但在可视化方面 python 可以让你一目了然这些分支的关系,这有助于你高效地进行调试
- 但是需要指出的是:在 python 中,哪怕逻辑被切断了,严格对齐的缩进依然有可能在视觉上欺骗你,让你误以为逻辑没断。下面这个思维练习将帮助我们更好的理解 python 控制流的逻辑。
ex_2.3.8_1 思考:elif 能否换成 if?
下面我们将来讨论控制流 control flow 在底层是如何判定的。
假设现在有四套分支(不含嵌套,逻辑同级):
if-elif-elseif-if-elseif-elifif-if
Case 1: if-elif-else,互斥分支(Mutually Exclusive Branching)
score = 85
# 这是一个完整的整体(互斥链条)
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
# 运行结果:B
# 逻辑:90的条件不满足,往下走;80的条件满足了,打印B,整个代码块结束,跳过 else。
在 tcl 语言视角下,则显然是一个完整整体:
if {$score >= 90} {
puts "A"
} elseif {$score >= 80} {
puts "B"
} else {
puts "C"
}
在cs中,这属于:互斥分支(Mutually Exclusive Branching)。
在 抽象语法树(AST, Abstract Syntax Tree) 中,if-elif-else 被解析为单一的复合控制结构。
- 语义特性(Short-circuit Evaluation): 它具备类似“短路求值”的特 性。解释器会自上而下顺序计算谓词(Predicate,即条件表达式)。一旦某个谓词评估为
True,程序将立刻执行对应的代码块(Block),随后强制跳出整个复合结构。后续的任何elif谓词将不再占用 CPU 时钟周期进行计算。 - 简单理解,就像是一个“通关安检”,只要在任何一关被拦下(条件为真),后面的关卡就直接废弃不看了
Case 2: if-if-else,悬挂的 else
weather = "下雨"
if weather == "下雨":
print("带伞")
if weather == "下雪":
print("穿羽绒服")
else:
print("天气不错,啥都不带")
如果 `weather` 是“下雨”:
- 第一个 `if` 满足,打印“带伞”。
- 第二个 `if` 判断“下雪”为 `False`。此时它与最下面的 `else` 紧挨,于是 `else` 会立刻执行。
- 最终输出:“带伞”,“天气不错,啥都不带”。 逻辑完全不对。
- 指导原则:在 Python 及多数 C-family 语言的语法解析器中,
else关键字遵循“就近词法绑定(Strict Lexical Binding)”原则。由于解释器自上而下的顺序来计算谓词,else永远只忠诚于紧挨在它上面的那一个if。 - 这种称为:语义绑定边界与 “悬挂的 Else”(The Dangling Else Binding)。我们强烈不推荐这么写,因为会引发控制流中最危险的逻辑漏洞之一。
- 因为
else没有自己的独立判定逻辑,它永远且仅仅作为其物理位置上方、最近的一个if(或elif,for,while)的补集(Complement)存在。
Case 3: if-elif,互斥分支但不具备完备性
补充: 互斥性(Mutual Exclusivity)与完备性/穷举性(Exhaustiveness)。
if-elif依然是绝对的“互斥分支”
在底层抽象语法树(AST, Abstract Syntax Tree)解析中,哪怕你没有写最后的 else,if-elif 依然被捆绑为同一个单一的复合控制结构。
**互斥(Mutually Exclusive)**的严格定义是:“这些分支中,最多只有一个会被执行”。
如果 if 的条件满足了,它执行完就会立刻跳出整个代码块,下面的 elif 连看都不会看一眼。
它们之间依然存在“你死我活”的排他性。
- 缺少了
else,它失去了什么?—— 失去了“完备性”
这就是 if-elif 和 if-elif-else 唯一的区别。
if-elif-else 既是互斥的,又是完备的。
它向解释器保证:“无论输入什么样的数据,必然有且只有一个分支会被触发”。那个 else 就是一张铺在最底层的兜底安全网(Catch-all fallback)。
if-elif 是互斥的,但不是完备的。
它向解释器保证:“这些分支最多只会触发一个,但也可能一个都不触发(即全部跳过)”。
Case 4: if-if,顺序独立分支(Sequential Independent Branching)
num = 10
if num > 0:
print("是正数")
if num % 2 == 0:
print("是偶数")
# 输出:
# 是正数
# 是偶数
当你改成两个 if 时,解释器会老老实实地把所有的条件都判断一遍,造成逻辑多重触发。
在 tcl 中,如果你把 elseif 拆掉,你就必须写成两个独立的 if 命令,由于 Tcl 没有像 Python 那样的强制缩进对齐约束,你会很自然地意识到它们是分开的:
if {$score >= 90} { puts "A" }
if {$score >= 80} { puts "B" } else { puts "C" }
在 cs 中,将 elif 替换为 if 后,变为 if-if,原本的复合结构被强行割裂为两个在内存空间和执行逻辑上完全独立的控制流单元。
- 语义特性: 无论第一个
if的谓词是否为True,程序控制流在退出第一个代码块后,强制要求对第二个if的谓词进行求值计算(Evaluation)。
Tips:
- 在性能区别上,例如在计算化学中,如果你的条件判断是运行一个耗时 5 分钟的函数(比如
if check_energy() < 0:),使用elif可以帮你省下大量的计算时间,因为只要上面满足了,下面的繁重计算直接短路跳过,elif谓词不再占用 CPU 时钟周期进行计算。而改成if,if,则所有的计算都会被强行执行一遍。 if-if-else除了易造成逻辑漏洞的情况下,if-if本身也可能造成计算资源浪费(Computational Overhead),在处理百万级原子的分子动力学模拟或庞大的张量网络时,这种 O(N) 的冗余谓词计算会造成极其显著的性能衰减。- 在进行复杂系统编程时,除非你的业务逻辑在数学上确实允许多重事件同时发生(Non-mutually exclusive events),否则不应使用连续的独立
if。使用if-elif-else不仅是语法规范,更是为了在编译器层面强制保证状态空间的互斥性与执行路径的唯一性。
ex_2.3.8_2 继续完善猜数小程序
Write a program that:
- Saves a secret number.
- Asks the user for a number guess.
- Prints whether the guess is too low, too high, or the same as the secret.
my answer:
secret = 7
guess = int(input('Enter an integer(1-10):'))
if guess == secret:
print('the guess is too same as the secret!')
elif guess > secret:
print('the guess is too high')
else:
print('the guess is too low')
我认为这个游戏还可以继续完善:
secret = 7
guess = int(input('Enter an integer(1-10):'))
while True:
if guess == secret:
print('the guess is too same as the secret!')
break
elif guess > secret:
print('the guess is too high')
else:
print('the guess is too low')
这个代码如果没有猜对,则一直打印例如 the guess is too high,而不询问换个数猜,因此也不会跳出循环!
secret = 7
guess = int(input('Enter an integer(1-10):'))
while True:
if guess == secret:
print('the guess is too same as the secret!')
break
elif guess > secret:
print('the guess is too high')
guess = int(input('Enter an integer(1-10):'))
else:
print('the guess is too low')
guess = int(input('Enter an integer(1-10):'))
上面加入了需要用户进行交互之后,则可以正常work!情况如下:
>>> secret = 7
... guess = int(input('Enter an integer(1-10):'))
... while True:
... if guess == secret:
... print('the guess is too same as the secret!')
... break
... elif guess > secret:
... print('the guess is too high')
... guess = int(input('Enter an integer(1-10):'))
... else:
... print('the guess is too low')
... guess = int(input('Enter an integer(1-10):'))
...
Enter an integer(1-10):9
the guess is too high
Enter an integer(1-10):6
the guess is too low
Enter an integer(1-10):7
the guess is too same as the secret!
Big idea
Debug early, debug often. Write a little and test a little. Don’t write a complete program at once. It introduces too many errors. Use the Python Tutor to step through code when you see something unexpected!
2.4 Summary
- Strings provide a new data type
- They are sequences of characters, the first one at index 0
- They can be indexed and sliced
- Input
- Done with the
inputcommand - Anything the user inputs is read as a string object!
- Done with the
- Output
- Is done with the
printcommand - Only objects that are printed in a
.pycode file will be visible in the shell
- Is done with the
- Branching
- Programs execute code blocks when conditions are true
- In an
if-elif-elif… structure, the first condition that is True will be executed - Indentation matters in Python!
2.5 homework
# Practice 1: What is the value of s1 and s2?
s1 = "a" + "b"
d = "hi"
e = " ana"
s2 = d + 2*e
# Practice 2: What are the substrings of s?
s = "ABC d3f ghi"
s[0:3:1]
s[0:4]
s[8:len(s):3]
s[2::-1]
# Practice 3: What does this print?
# Note that a += b is the same as a = a + b
# answer = ''
# x = 11
# # try with y = 2 and y = 12
# y = 2
# if len(str(x)) == len(str(y)):
# if y != 0 and x%2 == 1:
# answer = answer + "x / y is " + str(x/y)
# elif x < y:
# answer += "\nx is smaller" # \n inserts a newline character in the string
# else:
# answer += "\ny is smaller"
# print(answer)
# Practice 4: Uncomment the code below and:
# What does it print when a = 6 and b = "6"
# What does it print when a = "1" and b = 1
# What does it print when a = 3 and b = 3
# What does it print when a = "1" and b = "1"
# if ( a == int(b) ):
# print("int conversion")
# if ( a == int(b) ) and ( str(a) == b ):
# print("int and str conversion")
# else:
# print("interesting")
Lecture 3: Iteration
这一讲的核心主题是 Iteration(迭代 / 循环)。
在 Lecture 2 里,我们已经学习了 branching(分支),即程序可以根据条件的真假来决定执行哪一段代码。分支的特点就是根据某个条件判断真假,评估一组代码或另一组,而且不是按照线性方式执行。现在我们要进一步学习:如何让程序重复执行一段代码。
3.1 Why iteration?
- Recapitulate branching!
- 设计一个小人探索地图走路的游戏,能实现如下功能:
- If you keep going right, you are stuck in the same spot forever (for example, like woods background)
- To exit, take a chance and go the opposite way (for examole, like exit background)
如果只使用 branching,我们可能会写出如下结构:
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
and so on and on and on...
else:
<set background to exit_background>
else:
<set background to exit_background>
else:
<set background to exit_background>
这段代码在逻辑上可以工作,但问题非常明显:
- 它只能处理有限次数的向右选择。
- 每多一次可能的选择,就要多嵌套一层。
- 程序结构越来越深,越来越难读。
- 这种写法违背了程序设计中的 DRY 原则:Don’t Repeat Yourself。
这段代码展示的是一种非常笨拙的写法:
如果玩家不断选择向右走,那么程序就需要不断嵌套更多层 if <exit right>:。显然,这是不可扩展的。
如果理论上玩家可能连续向右走一万次,那么我们不可能手写一万层 if。
这就引出了本讲的核心思想: 当某段逻辑需要反复执行时,应当使用 loop(循环)来表达,而不是手动复制或无限嵌套代码。
同样的 Zelda / Lost Woods 逻辑,可以用 while 循环写得更加自然简单:
while <exit_right>:
<set background to woods_background>
<ask user which way to go>
<set background to exit_background>
- Zelda, Lost Woods tricks you
- If you keep going right, you are stuck in the same spot forever
- To exit, take a chance and go the opposite way
这里的意思是:
- 只要玩家还在选择 right,就一直留在 woods background。
- 每次循环都重新询问用户接下来往哪边走。
- 一旦用户不再选择 right,循环条件变成 False,跳出循环,设置背景为 exit_background。
这就是循环的价值: 当某个条件持续为真时,重复执行同一段代码。
3.2 while loops
3.2.1 Example: binge all episodes of one show
课件中用 Netflix 追剧的例子(见讲义 lecture 3, pp.7)来解释 while 循环:
- Netflix: start watching a new show
- There are more episodes to watch? (是否还有下一集?)
- yes → Play the next one (继续播放下一集)
- no → Suggest 3 more shows like this one (播完了,推送三个猜你喜欢)
这个例子很好地展示了 while 的语义:
while 不是“执行一次”,而是“只要条件还成立,就一直执行”。
3.2.2 Control flow: while loops
- 回忆 tcl 语言中我们接触过的控制流:TCL 中的控制流和 C 语言类似,包括
if、while、for、foreach、switch、break、continue、return等命令。
while 循环的一般结构如下:
while <condition>:
<code>
<code>
...
<condition>evaluates to a Boolean- If
<condition>isTrue, execute all the steps inside thewhilecode block - Check
<condition>again - Repeat until
<condition>isFalse - If
<condition>is neverFalse, then will loop forever!!
中文理解:
- 先检查
<condition>的值。 - 如果条件为
True,执行在相应的缩进内的代码块。 - 执行完代码块后,重新回到
while那一行,再次检查条件。 - 如果条件仍然为
True,继续执行。 - 如果条件变成
False,跳出循环,执行循环后面的代码。 - 如果条件永远不会变成
False,程序就会进入 infinite loop(无限循环)。
while 的关键不是“重复”,而是“根据条件决定是否继续重复”。
3.2.3 while loop example: Lost Forest
讲义 (lecture 3, pp.9) 给出了一个 Lost Forest 的例子:
You are in the Lost Forest.
************
************
left <- ☺ -> right
************
************
Go left or right?
程序如下:
where = input("You're in the Lost Forest. Go left or right? ")
while where == "right":
where = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")
这段代码的执行逻辑:
- 程序先询问用户:
where = input("You're in the Lost Forest. Go left or right? ")
由于 input() 永远返回字符串,因此 where 绑定的是一个 str 类型对象。
- 检查循环条件:
while where == "right":
如果用户输入的是 “right” (注意是字符串的相等),条件为 True,进入循环。
- 在循环内部再次询问:
where = input("You're in the Lost Forest. Go left or right? ")
这一步非常关键。
它使得变量 where 的值有机会发生变化,从而使循环有机会终止。
如果用户最终输入的不是 “right”,比如 “left”,那么: 变成
False,循环结束。跳出循环后执行:
print("You got out of the Lost Forest!")
因此,可能的运行过程如下:
You're in the Lost Forest. Go left or right? right
You're in the Lost Forest. Go left or right? right
You're in the Lost Forest. Go left or right? left
You got out of the Lost Forest!
Big Idea
在 while 循环里,通常必须有某个变量在循环体内被更新。
否则,如果条件一开始为 True,如果没有引入 break 等机制,则它可能永远都是 True,导致无限循环。
ex_3.2.3_1 You try it: What is printed when you type “RIGHT”?
where = input("Go left or right? ")
while where == "right":
where = input("Go left or right? ")
print("You got out!")
- What is printed when you type “RIGHT”?
如果用户输入的是 “RIGHT”,注意这里是全大写。Python 的字符串比较是 case-sensitive(大小写敏感) 的。
因此 "RIGHT" == "right" 的结果是: False。故循环不会被执行,程序直接跳到最后一行。所以输出为:
Go left or right? RIGHT
You got out!
Note: “RIGHT”、“Right”、“right” 在 Python 中是三个不同的字符串。如果希望找到解决方法呢?
- 如果希望用户输入大小写都可以接受,可以使用
.lower()方法; .lower()会把用户输入转换成小写字符串
例如下面就可以实现自动将用户输入的字符串转换为小写,解决了上述的问题:
where = input("Go left or right? ").lower()
while where == "right":
where = input("Go left or right? ").lower()
print("You got out!")
- 转换大小写的两个神器(触发这些函数的条件是只要跟在字符串后面即可):
.lower()将前面的字符串通通转换为小写 lowercase.upper()将前面的字符串通通转换为大写 uppercase
例如:
>>> "Right".lower()
'right'
>>> "right".upper()
'RIGHT'
3.2.4 while loop example: countdown-like repetition
课件(内存云图见 lecture 3, pp.11)给出如下例子:
n = int(input("Enter a non-negative integer: "))
while n > 0:
print('x')
n = n-1
假设用户输入:Enter a non-negative integer: 4,程序执行过程如下:检验 boolean,判定为真,进入循环,且每一次循环会打印一个x,执行 n = n - 1 后,内存里会逐个创建4、3…。直到为0 时,条件判定为 False,终止 while,且不打印 x。
最终输出:
>>> n = int(input("Enter a non-negative integer: "))
... while n > 0:
... print('x')
... n = n-1
...
Enter a non-negative integer: 4
x # 对应 n 为 4
x # 3
x # 2
x # 1
# 不打印了,此时 n 在内存里为 0
这里的变量 n 承担了两个角色:
- 它是循环条件的一部分:n > 0
- 它也是循环进度的记录器:每次循环后 n = n-1
这类变量常被称为
loop variable(循环变量) 或control variable(控制变量)。
3.2.5 Infinite loop and termination
对于上面的例子,请思考:What happens without last line n = n-1?
n = int(input("Enter a non-negative integer: "))
while n > 0:
print('x')
由于没有终止 while 循环的语句,例如 break 或使循环变量得到更变的机会,故不难想象其结果一定是无限循环打印出来的 x,其结果可能如下:
>>> n = int(input("Enter a non-negative integer: "))
... while n > 0:
... print('x')
...
Enter a non-negative integer: 6
x
x
x
x
x
x
... # infinite loop!!!
如果不小心写出了无限循环,程序会一直运行下去。
在 VS Code / Spyder / shell 中,如果程序停不下来,可以:
- 使用 Ctrl + C
- macOS 可用 Cmd + C 或 Ctrl + C
- 在 IDE 的运行窗口点击红色停止按钮
例如下面的代码:
- Run this code and stop the infinite loop in your IDE (Integrated Development Environment, 集成开发环境):
while True:
print("noooooo")
由于 True 永远是 True(在有些语言中,例如 tcl 等,对于 True 值可以用 1 来代替,False 可以用 0,因此可以写成 while {1} {...}),所以循环条件永远不会变成 False。程序会一直打印,直到你手动终止程序:
noooooo
noooooo
noooooo
noooooo
...
Big Idea
while loops can repeat code inside indefinitely!
Sometimes they need your intervention to end the program.
3.2.6 You try it: sad face counter
Question:
- Expand this code to show a sad face when the user entered the while loop more than 2 times.
- Hint: use a variable as a counter (任务:创建一个计数器,可以记录循环次数并打印出 sad face)
原始代码:
where = input("Go left or right? ")
while where == "right":
where = input("Go left or right? ")
print("You got out!")
my homework:
为了避免大小写的问题,我们可以用到 ex_3.2.3_1 中介绍过的例子,引入 .lower()。
小技巧:
a = a + b等价于a += b
现在有个问题:下面这两个代码的区别在哪? 版本1:
# version 1
where = input("Go left or right?").lower()
sadsad = 0
while where == "right":
if sadsad > 2:
print("sad sad! :(")
where = input("Go left or right?").lower()
sadsad += 1
print("You got out!")
# 执行的输出结果
Go left or right?right
Go left or right?right
Go left or right?right
Go left or right?right
sad sad! :(
Go left or right?left
You got out!
版本2:
# version 2
where = input("Go left or right?").lower()
sadsad = 0
while where == "right":
sadsad += 1
if sadsad > 2:
print("sad sad! :(")
where = input("Go left or right?").lower()
print("You got out!")
# 执行的输出结果:
Go left or right?right
Go left or right?right
Go left or right?right
sad sad! :(
Go left or right?left
You got out!
版本 1 是“先判断,再更新计数器”;版本 2 是“先更新计数器,再判断”。所以它们的 sad sad! :( 会在不同的时机出现。、
- 核心要点:打印
sad sad! :(时,sadsad的量是多少? - 对于版本1,它不是一进入循环就立刻加一,而是在循环快结束时才加一,因此打印出
sad sad! :(的if分支和sadsad += 1的逻辑有一定的错位。所以在版本 1 中,sadsad 记录的其实是:已经在前面几轮循环中完成过多少次“再次询问”?
版本1的过程图可以看下表,因此要等到第 4 次进入 while 循环时才打印:
| 用户输入 | 进入 while? | 判断时 sadsad | 是否打印 sad | 本轮结束后 sadsad |
|---|---|---|---|---|
第 1 次输入 right | 是 | 0 | 否 | 1 |
第 2 次输入 right | 是 | 1 | 否 | 2 |
第 3 次输入 right | 是 | 2 | 否 | 3 |
第 4 次输入 right | 是 | 3 | 是 | 4 |
第 5 次输入 left | 否 | 不进入循环 | 不判断 | 停止 |
- 版本2是一进入循环,立刻
sadsad += 1,所以在版本 2 中,sadsad记录的是:用户已经输入了多少次right,也就是进入while循环的次数。 - 所以版本 2 在第 3 次输入 right 时就打印,更符合题目的业务要求。
版本2的过程图可以参见下图:
| 用户输入 | 进入 while? | 先执行 sadsad += 1 后 | 是否打印 sad |
|---|---|---|---|
第 1 次输入 right | 是 | 1 | 否 |
第 2 次输入 right | 是 | 2 | 否 |
第 3 次输入 right | 是 | 3 | 是 |
第 4 次输入 left | 否 | 不进入循环 | 停止 |
而下面这个例子是不对的,因为如果一开始默认是0,无法进入 if 分支,则永远触发不了 sadsad += 1:
where = input("Go left or right?")
sadsad = 0
while where == "right":
if sadsad > 2:
print("sad sad! :(")
sadsad += 1
where = input("Go left or right? ")
进一步思考: 如果希望只在“超过两次”之后显示一次 sad face,可以写成:
where = input("Go left or right? ")
counter = 0
while where == "right":
counter += 1
where = input("Go left or right? ")
if counter > 2:
print(":(")
print("You got out!")
运行示例:
Go left or right? right
Go left or right? right
Go left or right? right
Go left or right? left
:(
You got out!
sad face 出现的 timing:循环结束后,根据总次数决定是否打印。
3.2.7 Control flow: while loops and number sequences
- Iterate through numbers in a sequence
课件给出如下代码,用 while 遍历一段数字序列:
n = 0 # Set loop variable outside while loop
while n < 5: # [n<5]: Test loop variable
print(n)
n = n+1 # Increment loop variable inside while loop; 更新 loop variable
# p.s. n = n+1 equivalent to n += 1
# 得到如下输出
0
1
2
3
4
缺少任何一部分都可能导致程序出错:
- 没有初始化:NameError
- 条件写错:可能一次都不执行,或执行太多次
- 没有更新:可能无限循环
3.2.8 A common pattern: factorial
一个计算阶乘的例子,实现目的如下:
- Find 4!
iis our loop variablefactorial(阶乘) keeps track of the product
这里要计算的是: $$4! = 1 \times 2 \times 3 \times 4 = 24$$
具体实现这个阶乘的代码如下:
x = 4
i = 1 # set loop variable outside while loop
factorial = 1 # 用来累计乘积;初始值必须是 1,因为乘法的 identity element 是 1
while i <= x: # test loop variable in condition
factorial *= i # keep a running product (eq to factorial = factorial*i)
i += 1 # increment loop variable inside while loop (eq to i = i+1)
print(f'{x} factorial is {factorial}') # 运用到之前的 f-string
# 输出结果如下
# 打印 4 的阶乘是 24
4 factorial is 24 # factorial 从 1*1 到 1*2 到 2*3 到 6*4,因此得到 24,i 循环到 5 终止
factorial *= i等价于:factorial = factorial * i- 类似地:
i += 1其等价于:i = i + 1 - 这类写法称为 augmented assignment(增强赋值)。
一个可视化过程值的变化的网址: Python Tutor LINK (https://pythontutor.com/visualize.html#mode=display)
3.3 for loops
3.3.1 Example: Are you still watching?
课件用 Netflix 的 “Are you still watching?” 机制(图可以参考 lecture 3, pp.19)来解释 for 循环。
场景:
- Netflix while falling asleep (it plays only 4 episodes if you’re not paying attention)
4 episodes in the sequence:- Still more eps in sequence -> Play the next episode -> 4 episodes in the sequence -> …
- Went through all eps in sequence -> Cuts you off
也就是说,当 Netflix 有一个明确的、固定长度的序列时,它可以依次播放其中的每一集。当这段序列播放完之后,就停止播放。
for 和 while 的区别在于:
while更像是:只要某个条件还成立(True),就一直重复做这件事。while根据条件判断做的循环。for更像是:对一个已知序列中的每一个元素,每个依次做一次,进行遍历。因此,for可根据序列结构做的循环。
3.3.2 Control flow: while and for loops
- Iterate through numbers in a sequence
课件比较了用 while 和 for 来遍历数字序列的写法。以前我们在学习 tcl 语言的时候早就了解到:事实上,不同的循环语句是可以写出实现同一个任务目的的代码的,只不过简明程度不一样。
- 回忆 tcl 语言中的
while与for:while:while test bodyfor:for init test reinit body- 参数
init是一个初始化脚本,第二个参数test是一个表达式,用来决定循环什么时候中断,第三个参数reinit是一个重新初始化的脚本,第四个参数body也是脚本。
- 参数
下面的两个代码目的是打印出从0到5的序列。
使用 while 的 verbose version(啰嗦版本):
# very verbose with while loop
n = 0
while n < 5:
print(n)
n = n+1
使用 for 的 shortcut version (简明版本):
# shortcut with for loop
for n in range(5):
print(n)
- 关于
range(5)的内容(尤其注意他没有打印出5)请参见 第 3.3.4 小节 的内容。
两段代码的输出完全一样:
0
1
2
3
4
差别在于:
while需要我们手动初始化 nwhile需要我们手动更新 n = n+1for会自动让 n 依次取序列中的值
因此,当我们明确知道要遍历某个序列时,for 通常更简洁、更不容易出错。
3.3.3 Structure of for loops
for 循环的一般结构如下:
for <variable> in <sequence of values>:
<code>
...
# 中文来看就是:
for <临时变量> in <一串值>:
<对每一个值执行一次代码块>
- Each time through the loop,
<variable>takes a valuefor循环里的临时变量名不是必须叫i、n或其他,它只是一个普通变量名。但最好取一个能表达含义的名字。
- First time,
<variable>is the first value in sequence - Next time,
<variable>gets the second value - etc. until
<variable>runs out of values
3.3.4 A common sequence of values: range
在 tcl 中,<sequence of values> 是往往一个列表。那么在 python 中又是怎么表述的呢?首先,我们来看下迭代对象有哪些。
广义的 iterable(可迭代对象):
- lists (这节将会我们介绍遍历数字序列
range()、遍历字符串str) - tuples
- dictionaries
- files
- sets
例如:字符串中的每一个字符都可以被循环(空格、符号等等都是所谓的字符串)。
for letter in "abc":
print(letter)
a
b
c
这里 "abc" 是一个字符串,也是一种 sequence。
letter 这个临时变量会依次绑定到:"a"、"b"、"c"
又例如:
>>> for test in "what the hell?":
... print(test)
...
w
h
a
t
t
h
e
h
e
l
l
?
- 除了上面所介绍的字符串可以被当作循环的序列,下面我们将介绍最常见的
for循环序列之一是:range()
for <variable> in range(<some_num>):
<code>
...
例如:
for n in range(5):
print(n)
- Each time through the loop,
<variable>takes a value - 事实上,这个
range(5)实际上的参数是range(0, 5, 1),对应从0开始(默认),直到5(但不包含5),步长为正方向的1(默认) - First time,
<variable>starts at 0 - Next time,
<variable>gets the value 1 - Then,
<variable>gets the value 2 - …
- etc. until
<variable>gets<some_num> -1- 千万注意!当你写
range(some_num)时,循环变量最后一次取得的值是some_num 的值-1后所得到的值,而不是some_num本身!这个十分类似前面我们在 slicing 中学过的s[start:stop:step],包含start,不包含最后的stop
- 千万注意!当你写
因此,range(5) 生成的整数序列是:0, 1, 2, 3, 4。注意:不包括 5。因此打印出来的结果应该是:
0
1
2
3
4
这和字符串 slicing 中的 [start:stop:step] 非常类似。
3.3.5 range(start, stop, step)
- Generates a sequence of ints, following a pattern:
range(start, stop, step)start: first int generatedstop: controls last int generated (go up to but not including this int)step: used to generate next int in sequence
- A lot like what we saw for slicing (回顾: 第2.1.4小节). Slicing had a similar syntax, but with colons
:not commas - Often omit start and step
- e.g.,
for i in range(4)等价于range(0, 4, 1): 从 0 开始,到 4 之前停止,每次加 1startdefaults to 0stepdefaults to 1
- e.g., for i in range
(-3,5): 从 -3 开始,到 5 之前停止,每次加1stepdefaults to 1
- e.g.,
range() 的三种写法(第一种最常见):
- range(stop)
- range(start, stop)
- range(start, stop, step)
深入思考! 关于 range() 的其他细节:
- 关于
s[]vsrange(),我们在 第2.1.3小节-拓展与补充 中进行了十分细致的补充与介绍。 start、step、step等,可以为负,但必须保证逻辑没问题,不会是空列表。range()是否合规、是否不是空串,可以利用list()检验,但不能直接用print(range()),因为range()与下标表达式的映射对象不同,其映射的 range object 是规则本身(如果存储大量的数字则会消耗内存!),参见 第2.1.3小节-拓展与补充-s[ ]vsrange()for可以直接从range()的对象中一个个自动取值,当然for的in也可以指向list(range())- 和字符串切片不一样的是,切片可以省略某个位置:例如
s[::1]或s[:2]或s[:2:1]。 range()是函数调用(function call),函数参数不能这样“留空”。函数调用的格式是function_name(arguments),也就是()这套语法。因此range(, 2, 1)是不合规的!
特别提醒:参考 第2.1.5小节 的内容,我们可以推得:对于空列表,如
range(6,3)(由于默认正方向 step 的1),也只会返回空串。
这一点我们可以用后面将会学到的 list 来检验(与 tcl 语言的比较类似):
# 利用 list 函数来返回列表
list(range(6, 3))
[] # 返回的是空串,说明是空列表
# 因此下面这个代码没有返回任何东西就结束了
>>> for i in range(6,3):
... print(i)
...
>>>
# 若想有效的表达,只能是 range(6,3,-1)
list(range(6,3,-1))
[6, 5, 4] # 注意打印的顺序是负方向的!
ex_3.3.5_You try it: what do these print?
# problem 1
for i in range(1,4,1):
print(i)
# 从 1 开始,每次加 1,直到但不包括 4,故应输出:1, 2, 3
# problem 2
for j in range(1,4,2):
print(j*2)
# 从 1 开始,直到但不包括 4,步长为 2,实际 list 中有 [1, 3],因此应该依次输出:2, 6
# problem 3
for me in range(4,0,-1):
print("$"*me)
# 注意到是负方向的,因此从4开始,直到0但不包含0,步长为-1,因此临时变量 me 遍历的 list 为 [4, 3, 2, 1]
# 而打印的话是 对字符串"$" 的 repeat,因此应该按顺序输出如下字符串:
# $$$$
# $$$
# $$
# $
3.3.6 Example: Running sum
- 本小节有内存云图,图形化表示出内存里对象的创建,具体参考可见 (lecture 3, pp.26-30)
mysumis a variable to store the running sumrange(10)makesibe 0 then 1 then 2 then … then 9
概念:什么是 running sum? running sum 可以理解为“滚动累加值”。也就是说,我们不是一次性写:0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 而是每次循环把当前的
i加到mysum里。
mysum = 0
for i in range(10):
mysum += i # augmented assignment(增强赋值)
print(mysum)
在内存云的图像上,首先是 i 绑定到了内存里的值为 0 的对象上,然后 for 循环根据 range(10) 函数回调的序列规则(range object),逐渐在内存里生成 1、2… 等新的对象(这也印证了前面我们说的,range() 映射并返回的对象是 range object,而非实际包含一堆数字的 list,是 for 循环自动抽取,按规则在循环过程中依次提供值)。而 mysum += i 的增强赋值,由于 Python 中的 int 是 immutable object(不可变对象),所以这一步并没有修改原先整数对象内部的值,而是让变量名 mysum 重新绑定到这个新结果上。
ex_3.3.6_1 You try it: sum between start and end
题目:
- Fix this code to use variables
startandendin therange, to get the total sum between and including those values. - For example, if
start=3andend=5then the sum should be 12.
mysum = 0
start = ??
end = ??
for i in range(start, end):
mysum += i
print(mysum)
题意即,能做到当 start = 3,end = 5时可以得到 12的结果。不难想到应该利用该加法:$mysum = 3 + 4 + 5$,而 range(3,5) 是不包含 5 的,因此可考虑到引入表达式,即写成 range(start, end+1)
- 这个例子想告诉我们:同
s[]一样,range()也可以嵌入表达式!
因此可以设计出版本1:
# version 1
mysum = 0
start = 3
end = 5
for i in range(start, end + 1):
mysum += i
print(mysum)
为什么初始的变量不可以放进循环里?变成如下表达:
# 错误的示范1
start = 3
end = 5
for i in range(start, end + 1):
mysum = 0
mysum += i
print(mysum)
- 错误的,因为
for循环区块里的 line by line,每次循环都把 mysum 重新初始化为0了!
# 错误的示范2
mysum = 0
for i in range(start, end + 1):
start = 3
end = 5
mysum += i
print(mysum)
- 错误的,因为在执行时,Python 需要先计算
range(start, end + 1),但是此时start和end还没有被定义,而是被写进了for循环的内部。所以如果前面没有定义过start和end,程序会直接报错:NameError: name 'start' is not defined。 - 如果侥幸运行成功,则可能前面示范的时候
start和end已经被定义。这也是交互式环境里很常见的“隐性状态污染”。- 删除和查询已存在的变量的方法可以参考 第1.17小节。这里直接
del start, end
- 删除和查询已存在的变量的方法可以参考 第1.17小节。这里直接
如果希望让用户输入:
# version 2
mysum = 0
start = int(input("Enter start: "))
end = int(input("Enter end: "))
for i in range(start, end + 1):
mysum += i
print(mysum)
注意反向区间!这里我们注意到一个问题,如果用户没注意到输入数值的顺序呢?例如,如果用户输入:start = 5 与 end = 3,那么由于 range(5, 4) 是正索引的空序列,循环不会执行。
若希望程序支持 start 大于 end 的情况,可以引入 if-else 完备的互斥分支的逻辑来写:
mysum = 0
start = int(input("Enter start: "))
end = int(input("Enter end: "))
if start <= end:
for i in range(start, end + 1):
mysum += i
else:
for i in range(start, end - 1, -1):
mysum += i
print(mysum)
例如,start = 5,end = 3。则计算:5 + 4 + 3 = 12
3.3.7 for loops and range: factorial implemented
计算目的: $$4! = 1 \times 2 \times 3 \times 4 = 24$$
在这一节,我们将把前面 第3.2.8小节 所写的 while 版本写的计算4的阶乘的小程序。把 factorial 的 while 实现和 for 实现放在一起对比。
Factorial implemented with a while loop:
x = 4
i = 1
factorial = 1
while i <= x:
factorial *= i
i += 1
print(f'{x} factorial is {factorial}')
Factorial implemented with a for loop:
x = 4
factorial = 1
for i in range(1, x+1, 1):
factorial *= i
print(f'{x} factorial is {factorial}')
这里 range(1, x+1, 1),当 x = 4 时,就是:range(1, 5, 1),于是 for 循环随着遍历生成:1, 2, 3, 4。
所以循环做的是:
factorial = 1
factorial = factorial * 1 # 1
factorial = factorial * 2 # 2
factorial = factorial * 3 # 6
factorial = factorial * 4 # 24
Big Idea
forloops only repeat for however long the sequence is.- The loop variable takes on these values in order.
- for 循环不会无限执行。
- 它只会按照 sequence 的长度执行固定次数。
- 每一次循环,loop variable 会依次绑定到 sequence 中的下一个值。
- 当 sequence 中的值用完后,循环自动结束。
3.4 while vs for
往往这需要考察 loop variable 是否适合已知序列。
while需要手动维护,i = 1 和 i += 1 可以,但更啰嗦;while适合当 不知道具体要重复多少次,只知道继续重复的条件是什么、什么时候可以停。- 需要手动控制循环条件,也可以用
while
for不需要手动更新,range自动给值,更自然for适合已经有一个明确的 sequence,知道要对其中每个值做一次操作,可预期循环次数的- 例如,当你知道要遍历的是:
1, 2, 3, ..., x,这种明确序列时,用for更简洁。 - 需要依次处理 range / string / list 等用
for
3.5 Summary
Looping mechanisms
whileandforloops
Lots of syntax today, be sure to get lots of practice!
循环让程序不再只是 line by line 地执行一次,而是可以根据条件或序列结构重复执行某段代码。
Whileloops- Loop as long as a condition is true
- Need to make sure you don’t enter an infinite loop
- while 的核心结构:
while <condition>:
<code>
<code>
...
Forloops- Can loop over ranges of numbers
- Can loop over elements of a string
- Will soon see many other things are easy to loop over(许多对象可以被遍历):
- listsc (这节我们介绍了遍历数字序列 sequence、遍历字符串 string、character)
- tuples(数组)
- dictionaries
- files
- sets
- 这些对象都属于更广义的 iterable(可迭代对象)
- for 的核心结构:
for <variable> in <sequence of values>:
<code>
...
3.6 Supplement: iteration, state, and termination
这一节是对 Lecture 3 的专业性补充,帮助建立更扎实的 CS 思维。了解一些更专业的词汇描述与概念。
3.6.1 Loop 的三个核心组成部分
一个可靠的循环通常有三件事:
- Initialization(初始化)
- Condition / sequence(循环条件或序列)
- Update(状态更新)
例如:
n = 0 # initialization
while n < 5: # n < 5 as condition
print(n)
n += 1 # update,用到了augmented assignment
3.6.2 Loop invariant(循环不变量)
在更专业的程序正确性证明中,我们经常会讨论 loop invariant(循环不变量)。
- loop invariant 循环不变量指的是: 在每次循环开始前都保持为真的某个性质。
例如计算 running sum:
mysum = 0
for i in range(10):
mysum += i
print(mysum)
当循环进行到某一步时,mysum 始终等于“已经遍历过的所有 i 的和”。更具体地说:
- 当已经处理完 0, 1, 2 时,mysum == 0 + 1 + 2
- 当已经处理完 0, 1, 2, 3 时,mysum == 0 + 1 + 2 + 3
这个性质在循环中始终成立,因此它就是一种 loop invariant。
3.6.3 Off-by-one error
循环中非常常见的错误叫 off-by-one error(差一错误)。
例如,我们想计算从 start 到 end,并且包含 end 的和,却在 range() 中写成 range(start,end),这种由于边界包含 / 不包含导致的错误,就是 off-by-one error。
3.6.4 Accumulator pattern
前面我们学习的 running sum 和 factorial 都属于一种常见模式:accumulator pattern(累积器模式)。
累积器模式通常有一个变量用来保存“目前累计出来的结果”,即创建一个计数器 counter,这个情景下称为 accumulator。
例如求和,这里 mysum 是 accumulator:
mysum = 0
for i in range(10):
mysum += i
选择初始值时,要注意运算的 identity element:
- 累加、加法的 identity element 是 0
- 阶乘、乘法的 identity element 是 1
3.6.5 Iteration and computational thinking
本讲的 iteration 是编程思维中的一个重要转折点。 在 Lecture 1 和 Lecture 2 中,程序主要是:
- do this
- then do this
- then maybe branch
- then do that
而从 Lecture 3 开始,程序可以表达:
- keep doing this until something changes 或者:
- do this once for every element in this sequence
这让我们可以写出真正有规模的程序,例如:
- 对 100000 个数据点求和
- 检查字符串里的每个字符
- 模拟一个游戏中的重复行动
- 迭代逼近一个数学解
- 遍历分子动力学轨迹中的每一帧
- 对文件中的每一行进行处理
体会:循环是从“写几行命令”走向“设计算法”的关键一步。
3.8 Homework
#### AT HOME ####
# Practice 1:
# Declare a variable x that stores an int > 0. Print all ints, one on each
# line, between 1 (inclusive) and x (inclusive) that are divisible by 5.
# For ex. if x = 15, it prints 5, 10, and 15.
# For ex. if x = 14, it prints 5 and 10.
# Practice 2:
# Declare a variable n that stores an int. Print the sum of all digits
# in n. Hint: you can get a digit at a time looking at the remainder
# when you divide n by 10.
# For ex. If x = 1234, print 10
#### END AT HOME ####
#### ANSWERS AT HOME ####
# Practice 1:
# Declare a variable x that stores an int > 0. Print all ints, one on each
# line, between 1 (inclusive) and x (inclusive) that are divisible by 5.
# For ex. if x = 15, it prints 5, 10, and 15. If x = 14, it prints 5 and 10.
# x = 15
# for i in range(1,x+1):
# if i%5 == 0:
# print(i)
# Practice 2:
# Declare a variable n that stores an int. Print the sum of all digits
# in n. Hint: you can get a digit at a time looking at the remainder
# when you divide n by 10.
# For ex. If x = 1234, print 10
# n = 1234
# total = 0
# while True:
# r = n%10
# total += r
# n = n//10
# if n == 0:
# break
# print(total)
#### END ANSWERS AT HOME ####
Lecture 4: Loops over Strings, Guess-and-Check, Binary
这一讲我们将聚焦于三个主题:
- Loops over strings
- Guess-and-check
- Binary
在 Lecture 3 中,我们已经学习了 while loop 和 for loop。
这一讲会继续拓展循环的使用方式:不仅可以 loop over numbers,也可以 loop over strings。
我们前面的 lecture 3 的 第 3.3.4 小节 里已经补充过 iterable 可迭代对象有哪几种。
随后,我们会用循环实现一种经典算法思想:guess-and-check(猜测并检查)。最后,引入 binary numbers,为后续理解浮点数误差做准备。
4.1 break & continue statement
4.1.1 What does break do?
break statement 的作用:
- Immediately exits whatever loop it is in
- Skips remaining expressions in code block
- Exits only innermost loop!
也就是说,
break会立刻跳出它所在的那一层循环。
p.s. 在之前我们学过的 tcl 语言中,
break会结束整个循环过程,并从循环中跳出;而continue只是结束本次循环。
- Python 里
break作用与 tcl 语言的一样,结束整个循环并跳出循环。 - 同时,python 也有
continue命令,结束本次循环,跳过本轮循环体中剩余代码,直接进入下一轮循环判断 / 下一轮迭代。
如果有 nested loops(嵌套循环),break 只会跳出最内层 innermost loop,而不会自动跳出所有 loop。
结构示意:
while <condition_1>:
while <condition_2>:
<expression_a> # Evalued when <condition_1> and <condition_2> are True
break
<expression_b> # Never evaluated (don't write code like this)
<expression_c> # Evaluated when <condition_1> is True
在上面的代码中:
- 如果执行到 break,则会跳出
while <condition_2>:这一层循环。 <expression_b>会被跳过。- 程序会继续执行外层循环里的
<expression_c>。
注意:break 不是跳出整个程序,而是跳出当前所在的 loop。
4.1.2 break example
课件给出如下例子:
mysum = 0
for i in range(5, 11, 2): # 从5开始,收录到10,步长为正向的2
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)
先看:range(5, 11, 2),它生成的序列是:5, 7, 9。loop round i 执行 mysum += i 后,程序第一轮就会在 if mysum == 5: 处触发 break,直接跳出 for loop(在这里就是 innermost loop)。所以:print(mysum) 输出:5。
4.1.3 continue example
一般是配合 branching 做跳过用的。
for i in range(5):
if i == 3:
continue
print(i)
其执行过程为:
i = 0 -> print(0)
i = 1 -> print(1)
i = 2 -> print(2)
i = 3 -> continue,跳过本轮后面的 print(i),进入下一轮
i = 4 -> print(4)
因此,打印的内容跳过了 print(3):
0
1
2
4
4.1.4 You try it: count even numbers in a range
题目:
- Write code that loops a
forloop over some range and prints how many even numbers are in that range. - Try it with:
range(5)range(10)range(2,9,3)range(-4,6,2)range(5,6)
Solution: 一种通用写法如下:
even_num = 0
for i in range(5):
# i is 0,1,2,3,4
if i%2==0:
even_num += 1
print(even_num)
这里判断偶数的条件是:i % 2 == 0 (% 是 modulo(取余))
Case 1: range(5)
所采用的代码如下,其他 case 同理。
count = 0
for i in range(5):
if i % 2 == 0:
count += 1
print(count)
range(5) 对应:0, 1, 2, 3, 4。故偶数是:0, 2, 4。所以输出:3
Case 2: range(10)
range(10) 对应:0, 1, 2, 3, 4, 5, 6, 7, 8, 9。偶数是:0, 2, 4, 6, 8。因此输出:5。
Case 3: range(2,9,3)
range(2,9,3) 对应:2, 5, 8。偶数是:2, 8。因此,输出:2。
Case 4: range(-4,6,2)
range(-4,6,2) 对应:-4, -2, 0, 2, 4。这些全是偶数,所以输出:5。
Case 5: range(5,6)
range(5,6) 只包含:5。由于 5 不是偶数,所以输出循环不变count:0。
4.2 Strings and loops
任务:
- Code to check for letter i or u in a string.
下面三个版本的代码都是做的是同一件事:
假设:
s = "demo loops - fruit loops"
Version 1: loop over index
- uses
rangeto iterate through index of s
s = "demo loops - fruit loops"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print("There is an i or u")
这里 range(len(s)) 会生成字符串合法 index 的范围。如果 s 的长度是 len(s),那么合法的正索引是:0, 1, 2, ..., len(s)-1。所以:s[index] 会依次取出字符串中的每个字符。
Version 2: loop directly over characters
- iterates through characters of
sdirectly
s = "demo loops - fruit loops"
for char in s:
if char == 'i' or char == 'u':
print("There is an i or u")
这个版本更直接。因为 string 本身就是一个 sequence of characters,所以 for loop 可以直接遍历字符串中的每个字符。
也就是说:for char in s: 会让 char 依次绑定到 s 里的每一个字符(包括空格)。
第二个版本实际上是更符合 python 风格的写法。
Version 3: use in
- iterates through characters of
sdirectly (most “pythonic”!) - 采用了两次序列为字符串的时候
s = "demo loops - fruit loops"
for char in s:
if char in 'iu': # 使用了 in 这个 keyword,去检验在 s 这个序列中是否含有 lowcase i or u。或者确切的了解,是判断当前字符 char 是否属于集合 'iu'(返回 True 或 False)?
print("There is an i or u")
这里:char in 'iu' 的意思是检查 char 是否属于字符串 'iu' 中的某个字符。这种写法也认为是一种 membership test,检测是不是字符串中的某个字母。
这种做法相对于 version 2 中的好处就是:如果我需要测试所含有的字符是较多的,例如是数字 0 到 9 中的一个,那么写多个 char == '1' or char == '2' or …显然是十分冗余的,这时候用 if ... in ... 就十分简洁了。
也就是检查:char == 'i' or char == 'u' .所以这三个版本本质上等价。
Which one is better?
一般来说,如果我们只是想逐个读取字符,不需要 index,那么更推荐:for char in s:。因为它更直观、更不容易写出 index error。如果确实需要知道每个字符的位置,才使用:for index in range(len(s)): 。
- 更多关于
in的了解:
对于 in,我们不仅了解到他可以是 for ... in ...,也可以是作为判断的条件。
a in b表示判断 a 是否是 b 的成员。 例如:
"x" in "abcx" # True
"ab" in "abcx" # True
"abcx" in "a" # False
这里有个特殊的情况,空字符串 '' 被认为是任何字符串的子串:
'' in 'abc'
True
'' in 'x'
True
'' in ''
True
此外,由于 string1 in string2 在语法上并没有错误,因此 string1 即便长度大于 string2 也不会报错。术语上,我们称 in 为 子串匹配:
'ab' in 'abc'
True
'bc' in 'abc'
True
'abc' in 'abc'
True
'abcd' in 'abc'
False
Big Idea
The sequence of values in a for loop isn’t limited to numbers.
4.3 Robot cheerleaders
课件给出一个 Robot Cheerleaders 的例子。 其核心代码如下:
an_letters = "aefhilmnorsxAEFHILMNORSX"
word = input("I will cheer for you! Enter a word: ")
times = int(input("Enthusiasm level (1-10): "))
for c in word: # c is a loop variable whose value is each letter that the user gave
if c in an_letters:
print(f'Give me an {c}: {c}')
else:
print(f'Give me a {c}: {c}')
print("What's that spell?")
for i in range(times): # i is a loop variable whose value is 0 through times-1, one at a time
print(word, '!!!!')
# 或写成 print(f"{word} !!!!")
下面我们来分别进行解读。
- First loop: loop over the word
for c in word:这里:
- c is a loop variable
- c 的值是 user 输入的 word 中的每一个 letter
- 每次循环,c 绑定到 word 里的一个字符
例如,如果:word = "cat". 那么 c 会依次是:'c', 'a', 't'
- Check whether to use a or an
if c in an_letters:
print(f'Give me an {c}: {c}')
# or:
# print("Give me an " + c + ":" + w)
else:
print(f'Give me a {c}: {c}')
an_letters 中列出的是读音上通常需要搭配 an 的字母,所以如果 c 在这个字符串里,就打印:Give me an ...,否则打印:Give me a ...。
这里的 in 是 membership test(成员测试),用于判断某个字符是否在某个字符串中。
- Second loop: loop over range(times)
for i in range(times):
print(word, '!!!!')
# 或写成 print(f"{word} !!!!")
这里:
- i is a loop variable
- i 的值从 0 到 times-1
- 每次循环打印一次
{变量 word} !!!!。这类打印的时候,实际上并没有用到我们的循环变量。
执行示例如下:
>>> an_letters = "aefhilmnorsxAEFHILMNORSX"
... word = input("I will cheer for you! Enter a word: ")
... times = int(input("Enthusiasm level (1-10): "))
... for c in word: # c is a loop variable whose value is each letter that the user gave
... if c in an_letters:
... print(f'Give me an {c}: {c}')
... else:
... print(f'Give me a {c}: {c}')
... print("What's that spell?")
... for i in range(times): # i is a loop variable whose value is 0 through times-1, one at a time
... print(word, '!!!!')
...
I will cheer for you! Enter a word: op
Enthusiasm level (1-10): 2
Give me an o: o
Give me a p: p
What's that spell?
op !!!!
op !!!!
4.4 You try it: count unique letters
题目:
- Assume you are given a string of lowercase letters in variable s.
- Count how many unique letters there are in the string.
- For example, if:
s = "abca". Then your code prints:3. (因为不同的字符是:a, b, c)
Hint:
- 通常对于此类程序需要设计一个额外的变量,它是一个包含你已经见过的所有内容的字符串。而每当见到一个之前没就见过的字母时,就将其添加到字符串变量中,标记其已经见过,之后使用这个变量来写其余部分。
- Go through(遍历) each character in
s. - Keep track of ones you’ve seen in a string variable.
- Add characters from
sto the seen string variable if they are not already a character in that seen variable.
my work: 需要明确一点,那就是对一些值得进行事先的显示声明与定义。
#仅仅满足原题目版——v1
word = input("Please enter a secret string:")
record = ''
unique_count = 0
for i in word:
if record not in i:
unique_count += 1
record += i
if unique_count > 1:
print(f"There are {unique_count} unique numbers.")
else:
print(f"There is {unique_count} unique number.")
如果写成 if i not in record 呢?
#仅仅满足题目版——v2
word = input("Please enter a secret string:")
record = ''
unique_count = 0
for i in word:
if i not in record:
unique_count += 1
record += i
if unique_count > 1:
print(f"There are {unique_count} unique numbers.")
else:
print(f"There is {unique_count} unique number.")
事实上,上面的作业第二个才是正确的。Python 只检查语法,不检查你的逻辑。我们要完成的是 i 是否是当前抽取的 record 的子集,因此逻辑应该为 i in record,然而因为一些特别的字符串(例如 word 为 aaaa 或 abc 则会凑巧算对)。更具体的论述,可以参见 第4.2小节
下面是课堂的 Solution:
s = "abca"
seen = ""
for char in s:
if char not in seen:
seen += char
print(len(seen))
具体过程如下:
| char | seen before | char not in seen? | seen after |
|---|---|---|---|
| ‘a’ | "" | True | “a” |
| ‘b’ | “a” | True | “ab” |
| ‘c’ | “ab” | True | “abc” |
| ‘a’ | “abc” | False | “abc” |
len(seen):
这是设计巧妙的一点。这里的 seen 是一个 accumulator,只不过它累积的不是 sum,而是“已经见过的字符”(通过字符串增添)。
我想比原先的任务多完善几点:
- 有多少个不同的字符串?
- 分别是哪些独立的字符串?
- 每个重复多少次?
- 打印的信息能体现上述几点,并且只打印一次
这种情况大概率需要利用到 s[] 结合 len(),或许还可以结合list或字典的方法。我的想法是循环s[i],返回的字符串如果相等就进行 repeat 计数,同时还可以返回出字符串(且print的时候下标运算也可以)。
word = input("Enter your string:")
record = ''
j = 0
repeat_count = 0 # 后续我们用 word[j:j+1] 遍历整个字符串,必然会循环到i(因为i从word中抽样),因此这里 repeat_count 需要初始值设为0,便于后续遍历
for i in word: # 之所以i不用事先定义(而下面的j却要定义,就是因为在 python 中的for循环已在这次 loop 中、这段代码 block 中抓取)
if i not in record:
record += i
while j < len(word): # 注意这里不能写成 j<= len(word),否则下面的j+1显然不对
if word[j:j+1] == i:
repeat_count += 1
# 事实上,上面的代码也能改写成 word[j] 返回字符串后,利用 in 来判断判断 i 是否是子集,或者根据计数器来判断
# s[j:j+1] 抓取当前的第j个字符串(输出单个,便于和 i 比较)
j += 1
print (f'{i}出现了{repeat_count}次!')
repeat_count = 1
print(f'独立的字符有{len(record)}个')
上述代码有严重错误,只记得重置 repeat_count,却没有重置 j,j += 1只作用于 while 的中止,然而终止后 j 没有在每一轮的 for 循环中重置,导致后续 while 直接跳过。并且事实上,我们完全可以先统计完独立的字符有几个,后续创建新的for循环来循环这几个独立的字符就行。并且创建的新的循环可以让我们把重置的初始化条件塞进去,让整体更为简洁。
# 完善的修改版本
# 模块一,抓取独立字符数量
word = input("Enter your string:")
record = ''
for i in word:
if i not in record:
record += i
print(f'独立的字符有{len(record)}个,分别是{record}')
# 模块二的做法一,注意初始值的重置建立在循环之上
for i in record:
j = 0
repeat_count = 0
while j < len(word):
if word[j:j+1] == i:
repeat_count += 1
j += 1
print (f'{i}出现了{repeat_count}次!')
# 第二个模块中的另一种写法:
for i in record:
count = 0
for j in word:
if j == i:
count += 1
print(i, count)
在 tcl 语言中,Tcl 没有 Python 那样方便的字典遍历(当然也有 dict),很多老 Tcl 程序员会先构造「不重复字符集合」,然后再二次遍历统计:
puts -nonewline "Enter your string: "
flush stdout
gets stdin word
set record ""
# 找出独立字符
foreach char [split $word ""] {
if {[string first $char $record] == -1} {
append record $char
}
}
puts "独立字符有 [string length $record] 个"
puts "分别是:$record"
# 统计每个字符出现次数
foreach char [split $record ""] {
set count 0
foreach x [split $word ""] {
if {$x eq $char} {
incr count
}
}
puts "$char 出现了 $count 次"
}
# 字典命令 `dict`,在新版本的 tcl 中,还有类似于 python 的字典功能:
# 一个简单的例子,并且使用了 [dict exists ...] 的命令:
set count_dict {}
foreach char [split $word ""] {
if {[dict exists $count_dict $char]} {
dict incr count_dict $char
} else {
dict set count_dict $char 1
}
}
事实上,更符合 python 写法的是利用字典(dictionary): 上面这个任务的目标,本质上可以是 key 存独立字符,value 存出现次数。字典是最自然的数据结构。
word = input("Enter your string:")
counts = {}
for char in word:
if char not in counts:
counts[char] = 1
else:
counts[char] += 1
print(f'独立的字符有 {len(counts)} 个')
print(f'分别是:{list(counts.keys())}')
for char in counts:
print(f'{char} 出现了 {counts[char]} 次!')
这里我们有必要引入字典的概念。
4.4.1 字典的引入简介
上面我们改进版的例子中,其字典 counts 被 char 循环遍历后,其大致结构会变成(假设前面用户输入了一串字符):
{
's': 2,
'j': 1,
'i': 3,
'o': 2
}
counts = {}是创建一个空字典 类似地,record = ''创建空字符串;numbers = []创建空列表。- 字典本质上是
key对应value:
{
's': 2,
'j': 1,
'i': 3,
'o': 2
# key: value
}
counts[char] = 1是添加一个新的项目(而上面的循环便是从word里遍历出来的。) 例如:
counts = {}
counts['s'] = 1
counts['j'] = 1
counts['i'] = 1
# 添加了三个类目 key,然后对应的是其项目的数量;因此如果你输入的是 print(counts['i'])将返回数量。
# 在上例中,由于 char 是遍历来的字符串,因此可以直接用 counts[char] 直接得之当前 char 所赋予的字符串在字典 counts 的数量(其具体的key对应的数量)
那么字典里的内容就会变成:
{
's': 1,
'j': 1,
'i': 1
}
类似于: (因此后续我们处理有类似表格结构的数据可以抽象成字典)
| key | value |
|---|---|
| s | 1 |
| … |
- 上面我们的得知,
counts[char] = ...如果 char 是新的 key,则为创建新项目,如果只是counts[char]则会直接评估为对应的项目的值。因此,我们也可以通过加减来调整项目的值:counts['i'] += 1也对应counts['i'] = counts['i'] + 1,本质计算就是1+1,随后字典里ikey 对应的 value 也从1变为2。 - 有个细节理解就是:value 并不是表示 字典里有几个 i,理解成 key 有几个重复单元的理解是不对的(即 key 不是收录了两个
i,i),而是我们自己拿来记录 i 出现次数的计数器,是实际对项目的赋值。 len(counts)可以得到字典counts里key的数量list(counts.keys())的意思:counts.key()实际上返回的是 所有 key 的集合,因此会返回例如dict_keys(['s', 'j', 'i', 'o']),但它不是 list,这是一种特殊对象(我们之前在学习range()时也遇到过这样特殊的对象)。- 由于不是严格正确的 list,需要进行函数的映射,利用
list()把它变成真正的列表:list(counts.keys()),此时会返回['s', 'j', 'i', 'o']这样正常的列表里。
- 事实上,Python 里很多时候甚至不用写
.keys(),前面我们写的for char in counts:,其完整地来写是for char in counts.keys():。之所以设计如此,是因为把设计者希望把整个字典看成「key 的集合(set)」 - 因此:
len(counts)等价于len(counts.keys())for char in counts:等价于for char in counts.keys():x in counts等价于x in counts.keys()list(counts)等价于list(counts.keys())
4.4.2 字典的一些函数
创建 counts = {},除了 counts.keys() 是默认的省略指向,还有(注意 counts 是我们创建的字典的名字,这个东西是可以随意更改的):
counts.values():- 得到所有 value,例如上例
counts.values()可以返回得到dict_values([2,1,3,2]),也是一种特殊的对象。需要list(counts.values())转换为列表,得到[2,1,3,2]
- 得到所有 value,例如上例
counts.items():- 上例
counts.items()可以返回得到字典的完全体:
- 上例
# 创字典
counts = {}
# 给字典里的 key 赋值 value
counts['s'] = 2
counts['j'] = 1
counts['i'] = 3
counts['o'] = 2
# 此时字典里的内容 belike
counts = {
's': 2,
'j': 1,
'i': 3,
'o': 2
}
counts.items()
# 返回的是一类特殊对象
dict_items([
('s',2),
('j',1),
('i',3),
('o',2)
])
# 此特殊对象可以被 list() 转换
list(counts.items())
# 于是得到
[
('s',2),
('j',1),
('i',3),
('o',2)
]
4.5 Summary so far
截至目前,我们已经掌握了实现很多算法所需的基本工具:
- Objects have types
- Expressions are evaluated to one value, and bound to a variable name
- Branching
- if, else, elif
- Program executes one set of code or another
- Looping mechanisms
- while and for loops
- Code executes repeatedly while some condition is true
- Code executes repeatedly for all values in a sequence
That is all you need to implement algorithms.
也就是说,借助 object、expression、branching、looping,我们已经可以开始表达真正的算法思想。下面我们将开始学习其他的内容,其目的是为了让我们的代码更整洁、更可读、更高效。
4.6 Guess-and-check
这是我们将前面的知识应用于我们的第一个算法 (algorithm),即猜测 (guess) 和检查 (check) 算法。
4.6.1 What is guess-and-check?
Guess-and-check 也叫:
- exhaustive enumeration (穷举枚举)
它适用于这样的问题:
- You are able to guess a value for solution
- You are able to check if the solution is correct
- You can keep guessing until:
- Find solution, or
- Have guessed all values
基本流程大致如下:
Initial guess ↓ Is your guess correct? ├── yes → done └── no → Choose the next guess (Be systematic, exhaustive enumeration)

小补充:关于文件结构树的符号
这是由于早起没有 GUI,为了在 console 中可以可视化而设计的符号。 在 mac 中,你可以借助如下技巧来实现输出这类符号:
- 可以安装
brew install tree,进入目标目录后执行:tree,变可以生成树状结构; - 可以在 mac 中寻找 系统设置 → 键盘 → 文本输入 → 文本替换,自行设置
- (最常用的方法)使用“字符检视器”,按
ctrl+cmd+space,然后搜索box drawings(一般输入box便有了) - 直接复制:
- ├:分支节点
- └:最后一个节点
- │:竖线
- ─:横线,通常连续输入两个 ──
效果如下:
├──
│
└──
4.6.2 Guess-and-check square root
这一节我们将接触到第一个案例,那就是找平方根。
- Basic idea
- Given an
int, call itx, want to see if there is anotherintwhich is its square root (如果存在,就认为是 perfect square,是完美的平方数) - Start with a
guessand check if it is the right answer
- Given an
例如,25 就是完美的平方数,因为有 5 这样的整数的平方根。下面我们将检查一个案例是关于 7 的,7 是否是 perfect square?
不难知道,这些猜测的 int 肯定不是答案,这样的猜测具有 randomness(例如先猜2,猜9,然后猜6…),而且也不 efficient。我们的诉求是充分利用计算机的性能(really harness the power of programming and computers being able to do things really quickly for us)。
- Be systematic
- To be systematic, start with
guess= 0, then 1, then 2, etc.
- To be systematic, start with
也就是说,我们不能乱猜,而是按照顺序系统枚举: 0, 1, 2, 3, 4, …
如果 x 是 perfect square(完全平方数),那么我们最终会找到它的 square root且停下。并且,如果不是,则需要知道什么时候停止。
- But what if
xis not a perfect square?- Need to know when to stop
- Use algebra – if
guesssquared is bigger thanx, then can stop (because if we don’t, we’re at risk of potentially doing somthing that will lead to an infinite loop)
例如: x = 10 系统枚举:
0**2 = 0
1**2 = 1
2**2 = 4
3**2 = 9
4**2 = 16
当:4**2 > 10
我们就可以停止,因为后面的 guess 大于4时,平方后只会更大且超过10,不可能再等于 10。

4.6.3 Square root with while loop
课堂上给出的 solution:
guess = 0 # 设置初猜
x = int(input("Enter an integer: "))
while guess**2 < x: # 设置 exit loop 条件
guess = guess + 1
if guess**2 == x:
print("Square root of", x, "is", guess)
else:
print(x, "is not a perfect square")
不过还有一些地方需要完善:
- Does this work for any integer value of
x? - What if
xis negative?whileloop immediately terminates
- So, our program could check for negative input, and handle differently
例如:x = -4,因为 guess = 0,所以 guess**2 < x 是 False,因此 while loop 会立刻停止。因此会打印:-4 is not a perfect square。这在 real number 范围内是合理的,但我们可能还想提醒用户是不是想输入正数 4。还有另一种情况是用户是否在讨论 imaginary numbers(虚数)。因此,我们需要在原有的代码上添加一些额外的代码来处理这些情况。
- Handle negative input with Boolean flag:
guess = 0
neg_flag = False
x = int(input("Enter a positive integer: "))
if x < 0:
neg_flag = True
while guess**2 < x:
guess = guess + 1
if guess**2 == x:
print("Square root of", x, "is", guess)
else:
print(x, "is not a perfect square")
if neg_flag:
print("Just checking... did you mean", -x, "?")
- Boolean flag
这里引入了:
neg_flag = False,我们称之为 Boolean flag,用来记录是否发生过某件事。虽然我们可以在上例中直接写if x > 0,但是会显得冗长,我们可以把一些事件抽象成 Boolean flag。变成if neg_flag,后续可对更新它的绑定(True or False)。
如果是写成下面这段话,有什么问题?
guess = 0
neg_flag = False
x = int(input("Enter a positive integer: "))
if x < 0:
neg_flag = True
while guess**2 < x:
guess = guess + 1
if guess**2 == x:
print("Square root of", x, "is", guess)
else:
print(x, "is not a perfect square")
if neg_flag:
print("Just checking... did you mean", -x, "?")
- 首先,如果用户输入的是负数,那么直接进入第一段字段,然而由于输入的是负数,因此 while 直接一开始条件为 False 终止,并由于 guess^2 > x,因此直接打印了
x is not a perfect square,无法完成我们提醒检查的目的。且由于 x>0 时,neg_flg没有分支可以进入为 True 的情况,所以整个逻辑是有严重错误的。
我认为更好的逻辑的版本:
- 我们可以转换下用户输入的负数,通过
abs()来进行矫正,然后重新进入循环 - 避免 dangle 问题
x = int(input("Enter a positive integer: "))
while x<0:
print("Just checking... did you mean", -x, "?")
y_or_no = input("Do you want to revise? Enter 'y' or 'no':")
if y_or_no == 'y':
x = abs(x)
else:
print("Ok, it will exit now.")
break
if not x<0:
guess = 0
while guess**2 < x:
guess = guess + 1
if guess**2 == x:
print("Square root of", x, "is", guess)
else:
print(x, "is not a perfect square")
事实上,上面这段话若输入 no 只循环一次,不会一直重复询问直到修正,就没必要用 while,直接用 if 即可(还可以省下 while 和 break):
x = int(input("Enter a positive integer: "))
if x<0:
print("Just checking... did you mean", -x, "?")
y_or_no = input("Do you want to revise? Enter 'y' or 'no':")
if y_or_no == 'y':
x = abs(x)
else:
print("Ok, it will exit now.")
if not x< 0: # 切记,这里不可以改成 else,否则若进入上面的 if 分支,则不会再执行 else 的逻辑了!!!因此若需要上面进行更新后,这里的逻辑还能执行,就必须用 if!
guess = 0
while guess**2 < x:
guess = guess + 1
if guess**2 == x:
print("Square root of", x, "is", guess)
else:
print(x, "is not a perfect square")
Big Idea
- Guess-and-check can’t test an infinite number of values.
- You have to stop at some point!
Exhaustive enumeration 只有在“可枚举且有停止条件”的问题上才适合使用。如果候选值是无限的,而且没有停止策略,程序就会无限运行。
4.6.4 Guess-and-check compared: while loop vs for loop
课件比较了 while loop 和 for loop 做 guess-and-check 的方式。

- while loop 的思路:
Initial guess
↓
Is your guess correct?
├── yes → break the loop, you're done
└── no → choose next guess
特点:
- 需要自己设置 initial guess
- 需要自己更新 guess
- 需要自己决定什么时候 stop
for loop 的思路:
Sequentially go through all possible guesses
↓
Check if the guess is correct
↓
Went through all values in sequence
特点:
- 已经有一个明确的 sequence of possible guesses
- for loop 自动让 loop variable 依次取这些值
- 不需要手动更新 iterant
如果我们已经知道所有可能的 guesses 在某个范围内,for loop 往往写出来的代码更干净。
4.6.5 You try it: secret number
mission:
- Hardcode a number as a secret number.
- Write a program that checks through all the numbers from 1 to 10 and prints the secret value if it’s in that range. If it’s not found, it doesn’t print anything.
- How does the program look if I change the requirement to be: If it’s not found, prints that it didn’t find it.
这里我们更推荐使用 for,而一开始设置 secret 的值是为了满足 hardcode 的要求。
- Version 1: if not found, print nothing
secret = 7
for i in range(1, 11):
if i == secret:
print("yes, it's", i)
如果 secret 不在 1 到 10 之间,就什么都不打印。
- Version 2: if not found, print not found
- 体会为什么要 set a boolean flag
found:
secret = 7
found = False
for i in range(1, 11):
if i == secret:
print("yes, it's", i)
found = True
if not found: # 这里要让 if 分支执行的条件是 True,若不改变 found 的 False 值,那么 not found 就是 True
print("not found")
值得一提的是,如果这里是 if found,则本质上等价于 if False。
- 语法上完全没问题,不会报错。但它的条件永远是假的,所以里面的代码永远不会被执行,相当于一段“死代码”。这种写法偶尔会用来临时屏蔽一段代码(相当于“注释掉”),不过更常见的还是直接用
#注释。 False,None,数字0、0.0,空字符串"",空容器[]、{}、()这些在if中均被当作假,语法没错但不执行相应的代码。
此外,上面第二个版本若写成:
secret = 7
for i in range(1, 11):
if i == secret:
print("yes, it's", i)
else:
print("not found")
则由于遍历,因此会打印真的信息和假的信息,这明显不符合我们的题意。因此上面第二个版本才会更合理,一旦遍历到了真密码,改变 found 的 boolean 值,毕竟全部都遍历了、循环结束了没找到的时候,才有报告的价值。
Big Idea
Booleans can be used as signals that something happened. We call them Boolean flags.
也就是说,Boolean 变量可以作为“信号灯”使用。 它不一定直接参与数学计算,而是用来记录某个事件是否发生。
例如:found = False,表示“目前还没找到”。一旦找到:found = True,后续程序就可以根据这个 flag 决定是否打印 “not found”。这可以让我们更符合直觉地维护代码。
4.6.6 Recompare agian: while loop or for loop?
- Already saw that code looks cleaner when iterating over sequences of values(i.e. using a
forloop)- Don’t need to set up the iterant yourself as with a while loop
- Less likely to introduce errors
- Consider an example that uses a
forloop and an explicit range of values
4.6.7 Guess-and-check cube root
4.6.7.1 Positive cubes
cube = int(input("Enter an integer: "))
for guess in range(cube+1): # guess 将从0开始遍历
if guess**3 == cube:
print("Cube root of", cube, "is", guess)
这个版本只适合处理非负整数的 perfect positive cube。因为这不是平方,有些数字的立方是可以为负数的,但在遍历的时候因 rang() 默认从 0 开始特性的原因,导致了无法取负。
4.6.7.2 Positive and negative cubes
若要支持负数的 cube,则只需要增添两行新的代码:
cube = int(input("Enter an integer: "))
for guess in range(abs(cube)+1): # assume it's positive
if guess**3 == abs(cube):
if cube < 0: # deal with negative cube here
guess = -guess # 前面先转换成绝对值,后面再次检验 cube,如果为负就转换 guess 符号
print("Cube root of " + str(cube) + " is "+str(guess))
4.6.7.3 Just a little faster: use break
事实上,我们还可以让代码跑的更快些!(虽然现在的计算机都是秒算这些玩意):
cube = int(input("Enter an integer: "))
for guess in range(abs(cube)+1):
if guess**3 >= abs(cube):
break # terminate search once know you have passed possible answer
if guess**3 != abs(cube): # check why you exited the loop and decide if the guess is not a perfect cube
print(cube, "is not a perfect cube")
else: # 只能是 guess*3 == abs(cube)
if cube < 0:
guess = -guess
print("Cube root of "+str(cube)+" is "+str(guess))
这里比前一个版本更快一点,因为一旦:guess**3 >= abs(cube) ,引入了 break 就可以停止继续猜了。如果在上面的例子中,仅仅只是 for guess in range(abs(cube)+1):,例如 cube 为 27,那么实际上猜到 3 的时候就已经有答案了,但仍会浪费一些时间去继续计算 guess = 4,5,...,27。
此外,上面这个例子体现了 guess 虽然没有被声明,但在循环遍历的时候就开始了 binding。break 后,显然 guess 值被 binding 为 guess**3 >= abs(cube)。因此做一个 if ... else ... 分支即可。
4.6.7.4 Another example: word problems
小时候常见的 word problem:
- Alyssa, Ben, and Cindy are selling tickets to a fundraiser
- Ben sells 2 fewer than Alyssa (Ben 比 Alyssa 少卖 2 张)
- Cindy sells twice as many as Alyssa
- 10 total tickets were sold by the three people
- How many did Alyssa sell?
- Could solve this algebraically, but we can also use guess-and-check
solution:
for alyssa in range(11): # check all possible values of `alyssa`,0-10
for ben in range(11): # for each value of `alyssa`, check all possible values of `ben`,0-10
for cindy in range(11): # for each pair of alyssa and ben, check all possible values,0-10
total = (alyssa + ben + cindy == 10) # 判断三者之和是否为 10 这个事件是否为 True(因为 ==)
two_less = (ben == alyssa-2)
twice = (cindy == 2*alyssa)
# 将三个问题转化成三个真假事件的 Booleans,并做循环,当三者为真的时候直接通过 if 打印出来
if total and two_less and twice: # solution foudn when all 3 hold
print(f"Alyssa sold {alyssa} tickets")
print(f"Ben sold {ben} tickets")
print(f"Cindy sold {cindy} tickets")
这里是three nested loops (三层嵌套循环)。
Note: Nested loops are slow for bigger numbers
- With bigger numbers, nesting loops is slow!
数值更大的例子,for example:
- Alyssa, Ben, and Cindy are selling tickets to a fundraiser
- Ben sells 20 fewer than Alyssa
- Cindy sells twice as many as Alyssa
- 1000 total tickets were sold by the three people
- How many did Alyssa sell?
- The previous code won’t end in a reasonable time
- Instead, loop over one variable and code the equations directly (解决慢的办法:循环其中一个变量,其他用方程来求,而不是暴力三循环)
如果仍然用三层循环:
for alyssa in range(1001): # 0-1000
for ben in range(1001):
for cindy in range(1001):
total = (alyssa + ben + cindy == 1000)
two_less = (ben == alyssa-20)
twice = (cindy == 2*alyssa)
if total and two_less and twice:
print(f"Alyssa sold {alyssa} tickets")
print(f"Ben sold {ben} tickets")
print(f"Cindy sold {cindy} tickets")
# 讲义里少了 break 条件
# 讲义少了 break 条件
# 讲义少了 break 条件
最多可能要检查大约:1001 * 1001 * 1001,也就是十亿级别的组合,非常慢。而且这个版本还有一个问题,即便满足条件,打印出来了,但由于上述代码没有引入 break,他会满足条件的时候打印出来,但由于循环没跑完,因此还会继续遍历上面的三层 for 循环!
需要解决几个问题:
- 即便打印出结果,仍旧在跑循环而不终止
- 只能利用、跑满单核,但不能利用多核
- 循环太多、效率太慢
【jimmy 的深度思考】 首先对于第一个问题——如何优雅跳出嵌套循环? 第一种解法是:
- 用 found 标记逐层 break
因为若只写
break,只会跳出最里面的for cindy ...,不会自动跳出for ben ...和for alyssa ...。
found = False # 先进行申明,重点学习如何利用到 boolean flag
for alyssa in range(1001):
for ben in range(1001):
for cindy in range(1001):
total = (alyssa + ben + cindy == 1000)
two_less = (ben == alyssa - 20)
twice = (cindy == 2 * alyssa)
if total and two_less and twice:
print(f"Alyssa sold {alyssa} tickets")
print(f"Ben sold {ben} tickets")
print(f"Cindy sold {cindy} tickets")
found = True
break
if found:
break
if found:
break
第二种解法:
- 用函数 +
return直接退出三层循环: 这是最干净的写法。因为 break 只能跳出当前这一层循环,而return可以直接结束整个函数。
def find_ticket_solution():
for alyssa in range(1001):
for ben in range(1001):
for cindy in range(1001):
total = (alyssa + ben + cindy == 1000)
two_less = (ben == alyssa - 20)
twice = (cindy == 2 * alyssa)
if total and two_less and twice:
print(f"Alyssa sold {alyssa} tickets")
print(f"Ben sold {ben} tickets")
print(f"Cindy sold {cindy} tickets")
return # 直接结束整个函数,不再继续三重循环
find_ticket_solution()
return的作用对象永远是 函数/过程(procedure),而不是循环。因此,如果这里要用到return来结束整个函数,那么就需要设计一个函数(通过def find_ticket_solution():)。- 此外,在 tcl 语言中,事实上我们也有提到过
return,起作用也是中止过程体,并返回过程体中最后执行的那条命令的返回值(可见我写的 tcl_note.md 中的第6.1.2小节)。需要注意的是,Python 没有自动返回最后一个表达式,但在很多语言,例如 Ruby、Julia、Rust 的return也能最后一个表达式自动成为返回值。
对于第二个问题,GIL 是 Python 解释器里的一把“全局锁”,它会让同一个 Python 进程里的多个线程不能同时执行 Python 字节码。所以对这种纯 CPU 暴力循环,threading 通常不能真正多核加速,要用 multiprocessing 开多个进程。
这是利用三个嵌套循环下的多线程版本:
from multiprocessing import Pool, cpu_count
# 这个函数只负责检查某一个 alyssa 值是否能找到解
# 注意:每个进程都会独立运行这个函数
def check_alyssa(alyssa):
# 对于当前这个 alyssa,仍然暴力枚举 ben 和 cindy
for ben in range(1001):
for cindy in range(1001):
total = (alyssa + ben + cindy == 1000)
two_less = (ben == alyssa - 20)
twice = (cindy == 2 * alyssa)
if total and two_less and twice:
# 找到答案时,把结果作为 tuple 返回
return alyssa, ben, cindy
# 如果这个 alyssa 没找到答案,就返回 None
return None
# multiprocessing 在 macOS / Windows 上必须写在这个 if 里面
# 否则子进程可能会反复重新运行整个文件
if __name__ == "__main__":
# cpu_count() 会返回你的电脑有多少个 CPU 核心/逻辑核心
# Pool(...) 表示创建一个“进程池”
# 可以理解成:找来多个 Python 工人一起干活
with Pool(cpu_count()) as pool:
# 把上面定义的 check_alyssa()函数中,range(1001) 里的 alyssa 值分给多个进程检查
# imap_unordered 的意思是:谁先算完,谁先把结果交回来,不要求按照 alyssa 顺序返回
for result in pool.imap_unordered(check_alyssa, range(1001)):
# 如果 result 不是 None,说明某个进程找到答案了
if result is not None:
alyssa, ben, cindy = result
print(f"Alyssa sold {alyssa} tickets")
print(f"Ben sold {ben} tickets")
print(f"Cindy sold {cindy} tickets")
# 找到答案后,终止进程池里的其他任务
pool.terminate()
# 跳出这个 for result 循环
break
最优雅的解决方案:
- More efficient solution:a mix of algebra & computation
- 只需要一次循环!
for alyssa in range(1001): # One loop over one variable
ben = max(alyssa - 20, 0) # replace loops with direct calculation for other 2 values
cindy = alyssa * 2
# 引入代数的限制+一些循环数值达一定条件时的截断,不用像上面的版本先排列组合,然后看哪个满足条件了
# 如果还要进一步优化,可以从数学层面考虑循环到哪的时候可以截断停止了,从而优化计算效率
if ben + cindy + alyssa == 1000:
print("Alyssa sold " + str(alyssa) + " tickets")
print("Ben sold " + str(ben) + " tickets")
print("Cindy sold " + str(cindy) + " tickets")
这里我们只 loop over 一个变量:for alyssa in range(1001):,然后根据题目条件直接计算:
ben = max(alyssa - 20, 0)
cindy = alyssa * 2
- 其中
max(alyssa - 20, 0)是为了避免 Ben 的票数变成负数。循环完后(guess 完)最后只检查(check):ben + cindy + alyssa == 1000。这样比三层 nested loops 快很多。 - 实测下来,上面的代码循环完(指打印出答案但仍等到 python 跑完循环)大概 1 min 以上(还是建立在 mac 或 9950x 这种单核十分强悍的机器),而且只跑满单核;而上面代数+循环的方案则瞬间算完!
- 上面这种做法,学术上来说,是利用数学约束减少搜索空间。
max()不是特殊函数,而是 Python 的max():ben = max(alyssa - 20, 0)指在alyssa-20和0中,取较大的那个。又例如:y = max(99,0),那么y就是99。- 数学意义上的理解,
max(x-20,0)可以看作是分段函数: $f(x)=\max(x-20,0)=\begin{cases}0,&x<20\x-20,&x\ge20\end{cases}$ - 在机器学习中这种形式以后会再次出现:ReLU 函数 $\mathrm{ReLU}(x)=\max(x,0)$ 这是深度学习中,最常见的激活函数。
本次案例的核心思想:
Brute Force
↓
利用条件减少变量或截断
↓
利用代数消掉循环(利用数学约束减少搜索空间)
↓
数学直接求解
- 暴力三重循环:O(n³)
- 减少 Ben 和 Cindy 循环:O(n)
- 代数直接求解:O(1)
Big Idea
You can apply computation to many problems!
我们不一定非要先手动列代数方程再解。 只要问题可以形式化成条件,就可以用计算机系统地搜索答案。
4.7 Binary numbers
4.7.1 Numbers in Python
目前我们已经见过 Python 中的两类数:
- int
- integers, 来表示整数。
- float
- reals, 用来近似表示实数。
Motivation: keep this in mind for the next context 了解下面发生的原因,将有助于我们去了解 binary numbers(二进制数字)、fraction(分数)、floats(浮点数)
Case 1:
>>> 0.1+0.4==0.5
True
>>> 0.1+0.2==0.3
False
Case 2:
x = 0
for i in range(10):
x += 0.1
print(x == 1)
print(x, '==', 10*0.1)
对于上面两个例子,其执行结果如下:
>>> x = 0
... for i in range(10):
... x += 0.1
... print(x == 1)
... print(x, '==', 10*0.1)
...
False
0.9999999999999999 == 1.0
>>> print(0.1+0.2)
0.30000000000000004
>>> print(0.2+0.3)
0.5
我们直觉上会认为:0.1 + 0.1 + … + 0.1,加 10 次应该等于:1。但 Python 中可能输出:为 0.9999999999999999。
这个称为 浮点数误差(floating point error)。后续我们将搞清楚:
- 它为什么会发生?
- 且由于它会发生,我们无法进行正常的等式比较(equivalency),也无法在浮点数之间使用等号(equal sign between floats),例如上面的0.1加十次,又或者是0.2+0.3…,该如何避免?
Big Idea
Operations on some floats introduces a very small error.
The small error can have a big effect if operations are done many times!
也就是说,某些浮点数运算会引入非常小的误差(由于浮点数在计算机内存中存储的方式导致)。单次看起来没什么,但如果重复很多次,误差可能累积并影响结果。 例如,在 gromacs 的分子模拟中,多次利用到浮点数存储,这可能会导致结果定性的错误!
4.7.2 A closer look at floats
- Python (and every other programming language) uses “floating point” to approximate real numbers
- The term “floating point” refers to the way these numbers are stored in computer
- Approximation usually doesn’t matter
- But it does for us!
- Let’s see why…
float 并不是真正的“数学实数(real)”,而是计算机用有限位数对实数做的近似表示。因此,浮点数在计算机中的存储方式将会影响到浮点数的值。
这解释了为什么:0.1 + 0.2 == 0.3,在 Python 中是:False。因为像 0.1、0.2 这样的 十进制小数,在 二进制浮点 表示中不一定能被精确表示。
4.7.3 Floating point representation
- Depends on computer hardware, not programming language implementation
- Key things to understand:
- Numbers (and everything else) are represented as a sequence of bits (0 or 1, binary). 之所以这样,是由于计算机硬件的构造方式
- When we write numbers down, the notation uses base 10, from 0 to 9.(人类日常写数字时使用的是十进制)
- 0.1 stands for the rational number 1/10 (有理数)
- This produces cognitive dissonance – and it will influence how we write code.
因此,实际计算得到的实数,我们将其转化为浮点数,计算机内部要把它转成二进制形式存储。但问题在于,并不是所有十进制小数都能被有限长度的二进制精确表示。
4.7.4 Why binary? Hardware implementation
- Easy to implement in hardware — build components that can be in one of two states
- Computer hardware is built around methods that can efficiently store information as 0’s or 1’s and do arithmetic with this representation
- like, a voltage is “high” or “low”
- like, a magnetic spin is “up” or “down”
- Fine for integer arithmetic, but what about numbers with fractional parts (floats)?
也就是说,binary 的硬件实现非常自然,要么高要么低,但如果要让硬件本身判断一个电压是 0 还是 1/10,还是… 将会困难的多得多,会引入许多误差。
因此,计算机硬件在这两个状态间进行切换将容易得多:0 or 1。
整数在 binary 中比较容易表示,但带有 fractional parts 的数,也就是 floats,就会复杂很多。
实际上,还有许多 位(bit),或者说 进制(我们在 tcl 语言教程中的第1.2.4小节讲过):
- 二进制(binary),只取 0,1
- 十进制 (Decimal),base 10,10-bits,人类的自然计数,取 0-9
- 十六进制 (Hexadecimal),有 16 个基本符号,核心规则是“逢十六进一”。 除了借用十进制的 0 到 9,为了凑齐 16 个符号,它还借用了英文字母来帮忙:A代表10,B代表11,C代表12,D代表13,E代表14,F代表15。
- 例如十六进制的 48,对应十进制就是 16*4+8=72
- 八进制(Octal),逢八进一,只使用 0、1、2、3、4、5、6、7 这 8 个数字符号。例如八进制的 110(不可下意识的拿十进制的百位数来看待!),就是
8*8+8=72(第一个1是从另一位进上来的,因此要有8次进位,而另一位也是8次进位来的,因此从左往右数的第一位 1 应该是 8*8,第二位 1 是 8,因此是 72)
Base 10 representation:
- Base 10 representation of an integer
- Sum of powers of 10, scaled by integers from 0 to 9
例如,对于 1507,在我们十进制看来就是(千位、百位、十位、个位 本质就是一层层以10为进制递送):
$1507 = 1 \times 10^3 + 5 \times 10^2 + 0 \times 10^1 + 7 \times 10^0 = 1000 + 500 + 7$
也就是说,十进制数的每一位都对应一个 10 的幂。
Binary representation is same idea in base 2
- Sum of powers of 2, scaled by integers from 0 to 1
也就是说,二进制和十进制的思想一样,只是 base 从 10 换成了 2。 二进制的每一位只能是:0 or 1
对于 1507,如果我们要以2进制来看待,则可以这么拆分:
$1507_{10} = 12^{10} + 12^{8} + 12^{7} + 12^{6} + 12^{5} + 12^{1} + 1*2^{0}
= 1024 + 256 + 128 + 64 + 32 + 2 + 1
= 2^{10} + 2^{8} + 2^{7} + 2^{6} + 2^{5} + 2^{1} + 2^{0}
= 10111100011_{2}$
(将 1507 拆分成多个 2 的次方。正如个十百千万,是由 $10^0, 10^1, 10^2, 10^3 …$ 构成数字来记录.那么二进制就可以抽象成 $2^0, 2^1, 2^2, 2^3 …$,因此对号入座,则可以填出 $10111100011_{2}$)
不难体会到,对于整数的组合,是没有问题的,但对于浮点数的组合(更为复杂),则上述从十进制转为二进制存储于计算器,再从计算器存储内转换到十进制的时候,就会导致误差的存在。
这里:
- 下标 10 表示 decimal / base 10
- 下标 2 表示 binary / base 2 例如,$1001_{2}$ 称为 1001 base 2.
4.7.5 Converting decimal integer to binary
这里我们会相比前一小节而言,讲述如何更系统地将十进制整数转换成二进制:
- We input integers in decimal, computer needs to convert to binary
- Consider example of:
- $x = 19_{10} = 12^4 + 02^3 + 02^2 + 12^1 + 1*2^0 = 10011_{2}$
计算机可以采取的实际方式,根据算法,将一个整数的数字转化为二进制:
- 下面顺序是从右往左看待数字 19:
- If we take remainder of x relative to 2, i.e.
x % 2, that gives us the last binary bit (odd -> 1, even -> 0),因此余数可以给出从左往右看的最后一位数为1,因为19为奇数,取模后为1。但从位运算上来说,我们从右往左记录,先得到了1 - If we then integer divide x by 2, i.e.
x // 2(整数除法,除完只保留整数),19 // 2 == 9, all the bits get shifted right- $x//2 = 9 = 12^3+02^2+02^1+12^0$,记为
1001,补上上一部的操作,从右往左 shifted over,因此实际为10011
- $x//2 = 9 = 12^3+02^2+02^1+12^0$,记为
- Keep doing successive divisions; now remainder gets next bit, and so on
(换个角度来看,例如上面得到的9,继续
9%2得到1便从右到左记录到 bit 中;继续计算,9//2,得到4,4%2得到0,记录0到 bit 中,以此类推:4//2得2,2//2得1,1//2得0)
具体该操作过程如下:
| x | x % 2 | binary bit | x // 2 |
|---|---|---|---|
| 19 | 1 | last bit,1 | 9 |
| 9 | 1 | next bit,1 | 4 |
| 4 | 0 | next bit,0 | 2 |
| 2 | 0 | next bit,0 | 1 |
| 1 | 1 | next bit,1 | 0 |
注意:通过 % 2 得到的 bit 是从右往左得到的。虽然得到的先后顺序是:1, 1, 0, 0, 1,但因为从右到左,二进制要反过来看:10011。所以:$19_{10} = 10011_{2}$
4.7.6 Doing this in Python for positive numbers
# 这个代码可以将正整数转换成二进制的数字
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num//2
注意代码细节!这里是把新 bit 加到 result 的左边,而不是右边。
牢记:因为 % 2 得到的是当前(从右往左的)最低位 bit,所以需要放到结果字符串的前面,功能实现上就是左刷新右保留,是使得结果符合人类从左往右阅读的习惯。 可以理解为多项式从0项开始拆解。
num = num//2 相当于把二进制表示整体右移一位(因为除2,对二进制来说就是进一位了)。
4.7.7 Doing this in Python and handling negative numbers
如果要处理负数的整数,则需要下面处理:
if num < 0:
is_neg = True
num = abs(num) # 先对其进行绝对值处理,后续打印再加回去负号
else:
is_neg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num//2
if is_neg:
result = '-' + result
4.8 Summary
- Loops can iterate over any sequence of values:
- range for numbers
- A string
- Guess-and-check provides a simple algorithm for solving problems
- When set of potential solutions is enumerable, exhaustive enumeration guaranteed to work eventually
- Binary numbers help us understand how the machine works
- Converting to binary will help us understand how decimal numbers are stored
- Important for the next algorithm we will see
4.9 Professional supplement: extra CS concepts behind Lecture 4
4.9.1 Search space(搜索空间)
在 guess-and-check 中,我们真正做的事情是:
在一组可能答案中逐个尝试,直到找到满足条件的答案。
这组“所有可能答案”就叫 search space(搜索空间)。
例如:
for guess in range(abs(cube)+1):
...
这里的搜索空间就是:
0, 1, 2, ..., abs(cube)
判断一个 guess-and-check 程序是否合理时,首先要问:
- 搜索空间是不是有限的?
- 搜索空间是不是足够覆盖所有可能答案?
- 搜索空间会不会太大,导致程序跑得很慢?
4.9.2 Brute force algorithm(暴力搜索算法)
Guess-and-check 在 CS 中常被称为 brute force algorithm(暴力算法 / 暴力搜索)。
它的思想很朴素:不使用复杂推理,直接把所有可能答案试一遍。
它的优点是:
- 容易理解
- 容易实现
- 不容易漏掉答案,只要搜索空间设对了
它的缺点是:
- 可能非常慢
- 搜索空间一大,运行时间会迅速增加
所以 brute force 常常是解决问题的第一个版本。先写一个暴力版本确认逻辑正确,再考虑如何优化。
4.9.3 Combinatorial explosion(组合爆炸)
当一个问题里有多个变量都需要枚举时,搜索空间会以乘法方式增长。
例如三层循环:
for alyssa in range(1001):
for ben in range(1001):
for cindy in range(1001):
...
理论上最多要检查:1001 * 1001 * 1001 种组合,也就是十亿级别。
这种候选组合数量突然暴涨的现象叫:combinatorial explosion(组合爆炸)。它是很多算法变慢的根本原因之一。
因此,一个很重要的优化原则是: 能通过条件直接算出来的变量,就不要再暴力枚举。
例如,如果题目已经告诉我们:A = 2 * B,那么就没必要再对 A 写一层 for loop。
4.9.4 Early stopping(提前停止)
break 背后对应一个重要算法技巧:early stopping(提前停止)。当我们已经知道继续搜索没有意义时,就应当立刻停止,而不是把所有可能性都试完。
例如:
for guess in range(abs(cube)+1):
if guess**3 >= abs(cube):
break
如果 guess3 已经大于或等于目标值,那么后面的 guess 只会更大,guess3 也只会更大。所以继续检查已经没有意义,可以提前停止。
这类优化虽然看起来简单,但在大规模搜索中会节省大量时间。
4.9.5 Linear search(线性搜索)
本讲中的很多 guess-and-check 其实都属于一种基础搜索模式:linear search(线性搜索)
它的特点是:从头到尾一个一个检查候选值(例如从1到10等等)。
线性搜索的特点是:
- 最好情况:第一个就找到
- 最坏情况:检查完整个序列才找到,或者根本没找到
- 平均情况:大约检查一半
后面学到更高效的搜索算法时,比如 binary search,就会看到它们和 linear search 的差异。
4.9.6 Sentinel value(哨兵值)
Boolean flag 是一种记录程序状态的方法。另一种常见技巧叫 sentinel value(哨兵值)。 我们在 第4.6.7.4小节中 的多线程版本中有利用过这个 sentinel value 技巧。
- Sentinel value 指的是: 用一个特殊值来表示“还没找到”“还没开始”“无结果”等状态。
例如:
answer = None
for guess in range(10):
if guess**2 == x:
answer = guess
if answer is None:
print("not found")
else:
print(answer)
这里: answer = None 表示目前还没有找到答案。None 就扮演了 sentinel value 的角色。 sentinel value 有时可以同时记录“是否找到”和“找到的结果是什么”。
因此,可以结合 A = None ... if A is None: ...
4.9.7 Decimal vs binary: representation is not value itself
Lecture 4 后半部分引入 binary,是为了说明一个重要事实:数字的“表示方式”不是数字本身。
例如,数学上的十九这个值,可以写成十进制:19,也可以写成二进制:10011。
它们表示的是同一个抽象数值,只是 notation 不同。
- 计算机底层处理的是 bit pattern,而在 Python 中看到的是更高层的 int、float 等对象。
4.9.8 Machine representation(机器表示)
计算机中的数据最终都要落到某种 machine representation(机器表示) 上。
例如:
- 整数可以表示成一串 bits
- 字符可以通过编码表表示成 bits
- 浮点数也通过特定格式表示成 bits
所以我们在 Python 中写:x = 0.1,看似是在保存数学上的 1/10,但底层实际保存的是一个有限长度的二进制近似值,这就是为什么浮点数会出现细小误差。
4.9.9 Approximation error(近似误差)
浮点数误差可以理解为一种:approximation error(近似误差)。它不是程序写错了,而是因为计算机使用有限 bits 近似表示某些实数。
例如,十进制中:1/3 = 0.333333333...,无法用有限位小数精确表示。类似地,二进制中很多十进制小数,比如:0.1,也无法用有限位 binary 精确表示。
计算机思维:
- 因此在数值计算中,常常不直接判断:
x == target,而是判断:abs(x - target) < epsilon,其中 epsilon 是允许误差范围。只要小于误差允许范围内即是允许的近似误差。
4.9.10 Summary of extra terms
| 术语 | 含义 |
|---|---|
| search space | 所有候选答案组成的集合 |
| brute force algorithm | 暴力枚举所有可能答案 |
| combinatorial explosion | 多变量组合导致搜索数量暴涨 |
| early stopping | 确定没必要继续时提前停止 |
| linear search | 从头到尾逐个检查 |
| sentinel value | 用特殊值表示“未找到”等状态 |
| machine representation | 数据在机器底层的表示方式 |
| approximation error | 有限表示导致的近似误差 |
Lecture 5: Floats and approximation methods
这一讲主要包含两个主题:
- Floats(浮点数)
- Approximation methods(近似方法)
首先从上一讲遗留的浮点数问题出发,解释为什么某些十进制小数无法被计算机精确表示;随后讨论如何在无法得到精确答案时,设计一个能够得到“足够接近”答案的算法。即,介绍近似算法。
5.1 Fractions
上节课我们已经展示了: Integers have straightforward representations in binary. The code was simple. 下面我们来看几个问题。
5.1.1 What does a decimal fraction mean?
for instance, 0.abc.
十进制小数 0.abc 的含义是:
$$
a\times 10^{-1}+b\times 10^{-2}+c\times 10^{-3}
$$
例如: $$ 0.375=3\times 10^{-1}+7\times 10^{-2}+5\times 10^{-3} $$
For binary representation, we use the same idea. 对于二进制小数,也使用相同的位值思想。
二进制中的 0.abc 表示:
$$
a\times 2^{-1}+b\times 2^{-2}+c\times 2^{-3}
$$
To put this in simpler terms,the binary representation of a decimal fraction f。要寻找十进制小数 $f$ 的二进制表示,本质上就是寻找一组只能取 0 或 1 的 $a,b,c,d,e,\ldots$,使:
$$f=0.5a+0.25b+0.125c+0.0625d+0.03125e+\cdots$$
也就是说,小数点右侧的每一个 binary digit 分别代表:
| 二进制位 | 位权 |
|---|---|
| 第 1 位 | $2^{-1}=0.5$ |
| 第 2 位 | $2^{-2}=0.25$ |
| 第 3 位 | $2^{-3}=0.125$ |
| 第 4 位 | $2^{-4}=0.0625$ |
| 第 5 位 | $2^{-5}=0.03125$ |
5.1.2 How to convert a fraction to binary
In decimal form:: $$ \frac{3}{8}=0.375=3\times10^{-1}+7\times10^{-2}+5\times10^{-3} $$
Recipe Idea:如果能够找到足够大的 2 的幂($2^{n}$),把小数乘成整数,那么可以先把这个整数转换成二进制(因为前面我们说过,整数可以完美地转化为二进制)。之后再除以同一个 2 的幂($2^{n}$),等价性地可以恢复。因此 2 有多少次的幂,就可以在转换后的二进制滑动小数点,使其可以恢复成小数点的位置。
下面举例 0.375 是如何存储的:
- 将
0.375乘以2**3:
0.375 * (2**3) == 3
即:$$0.375\times 2^3=3_{10}$$
把十进制整数
3转换成二进制:$$3_{10}=11_2$$再除以
2**3,也就是把二进制小数点向左移动三位(shift right three spots): $$11_{2} \div 2^{3} = 0.011_{2}$$
所以:$$0.375_{10}=0.011_2$$
验证:$$0.011_2=0\times 2^{-1}+1\times 2^{-2}+1\times 2^{-3}=0.25+0.125=0.375$$
But not every fraction can become an integer!!!
- 如果不存在某个整数 $p$,使:$$x\times 2^p$$ whole number 成为整数,那么这个数的内部二进制表示就必须是一个 approximation(近似值)。
- 此外,如果我们要写代码,需要考虑:
- 什么样的判定范围内才是满足我们近似的条件?
- 如果这个
p十分大,该怎么办,遍历到什么时候结束?
这里还隐含了一个假设:我们输入的十进制小数本身是完全精确的,而不是在被 Python 读取前,就已经转换成 float 而变成近似值的值。
因此,floating-point conversion works:
- 对于
3/8这样的数,可以精确完成; - 对于
1/10这样的数,无法精确完成; - 原因是前者存在某个 2 的幂能把它变为整数,而后者不存在。
从分数的角度看:一个最简分数只有在分母的质因数全部为 2 时,才有有限长度的二进制小数表示。 例如:
- $3/8$ 的分母是 $2^3$,所以二进制表示有限;
- $1/10=1/(2\times5)$,分母含有质因数
5,所以二进制表示无限循环。
5.1.2.1 案例分析和repr()、format()、math.isclose()、.hex()
Key: Python 读取十进制字面量时,会将其转换并舍入为最接近的二进制浮点数,因此真正进入后续计算的是近似值。
我们现在有必要来合理的解释为什么下面发生了如此情况:
>>> 0.3+0.1==0.4
True
>>> 0.1+0.2==0.3
False
>>> print(0.3+0.1,0.4)
0.4 0.4
>>> print(0.2+0.1,0.3)
0.30000000000000004 0.3
需要明确一点,0.1、0.2、0.3、0.4 等均无法被精确被二进制表示,因此他们都是二进制浮点近似值。
但这里的关键在于 == 比较的不是“它们是否都精确”,而是比较两边最终存入内存的浮点数位模式是否完全相同。
因此有可能两边实际都是浮点数存储,但有些情况两边近似值的存储结果相等(如上面的 0.3+0.1==0.4),而有些情况例如左侧等式的两个浮点数加和完却和右侧等式的浮点数不一致,有一点误差,导致了不相等(例如上面的 0.2+0.1==0.3 就是这种情况)。
可以用
.hex()函数来查询 python 的底层十六进制浮点数
例如:
# 十六进制
>>> 0.1.hex()
'0x1.999999999999ap-4'
>>> 0.3.hex()
'0x1.3333333333333p-2'
>>> 0.4.hex()
'0x1.999999999999ap-2'
当计算 0.1 + 0.3 == 0.4 时,其实际步骤为:
- 取 0.1 的浮点近似值;
- 取 0.3 的浮点近似值;
- 将二者相加;
- 再把结果舍入到最接近的可表示浮点数。 这一次,舍入后的结果恰好就是 Python 存储 0.4 时选择的那个浮点数:
# 十六进制
>>> (0.1 + 0.3).hex()
'0x1.999999999999ap-2'
>>> 0.4.hex()
'0x1.999999999999ap-2'
显然,这里并不代表计算结果是数学意义上精确的 0.4,只代表:float(0.1) + float(0.3) 取舍与 float(0.4) 落在了同一个可表示浮点数上。
而对于 0.1 + 0.2 == 0.3:
# Python 首先把字符序列 "0.1" 解析为数学意义上的十进制数,然后将它舍入为最接近的二进制浮点数
>>> (0.1 + 0.2).hex()
'0x1.3333333333334p-2'
>>> 0.3.hex()
'0x1.3333333333333p-2'
# 注意最后一位不一样!
所以它们是两个相邻但不同的浮点数,所以会判 False。更具体来说,0.1 + 0.2 的精确浮点运算结果在舍入后,落到了 0.3 上方的下一个可表示浮点数,而不是 Python 用来表示 0.3 的那个浮点数。
因此,这里存在两层需要区分的概念:
- 源代码中的十进制字面量所表示的数学值(我们人类的计数习惯,在代码的世界里是“精确“的);
- 该字面量转换后真正存入内存的二进制浮点值(实际存储的是近似值)。
事实上,十进制输出还会隐藏细节 例如,Python 打印:
>>> 0.4 # 这个就是我们输入的十进制小数本身是完全精确的
0.4 # 存储到内存的时候已经是近似的浮点数了!
看起来返回的是 0.4 了,但这并不意味着内存中保存的是精确的 0.4。**Python 的 repr() 会选择一个足够短的十进制字符串,使这个字符串重新转换为浮点数后,仍然得到原来的浮点值。**因此,它打印 0.4,而不是显示全部误差。
我们可以用 format() 函数来进行查询:
>>> format(0.4, '.20f') # 打印小数点后20位的浮点数
'0.40000000000000002220'
>>> format(0.1 + 0.3, '.20f')
'0.40000000000000002220'
# 两者虽然都不是数学意义上的精确 0.4,但它们是完全相同的近似值。
在实际代码中比较浮点结果,通常应使用:
import math
math.isclose(0.1 + 0.2, 0.3)
# 会返回 True
几个函数的小总结与补充:
format():用来按照指定格式,把一个值转换成字符串。
- 基本语法:
format(value, format_spec) format()返回的是 字符串类型,str- 例如:
x = 3.1415926保留两位小数:print(format(x, ".2f")),输出:3.14。其中:.2表示保留 2 位小数f表示使用定点小数格式
- 查看浮点数更多位数:
print(format(0.1, ".20f"))输出类似:0.10000000000000000555,这可以帮助我们看到浮点数实际存储值附近的十进制展开。 常见格式:
format(3.14159, ".3f") # '3.142',有四舍五入
format(1234.5, ",.2f") # '1,234.50'
format(0.25, ".1%") # '25.0%'
format(255, "b") # '11111111'
repr():返回一个对象的“正式字符串表示”,主要用于调试和观察对象的真实结构。
- 基本语法:
repr(object) repr()返回的是 字符串类型,str 例如:
text = "hello\nworld"
print(text)
print(repr(text))
# 输出得到:
hello
world
'hello\nworld'
区别在于:
print(text)会真正执行换行repr(text)会显示字符串中的转义字符\n,且也会显示出原本的字符串引号。
然而对于浮点数:print(repr(0.1)),现代 Python 通常输出:0.1。
这不代表它在内存中是精确的 0.1。Python 会选择一个尽可能短、但重新转换后仍能得到同一个浮点数的字符串。这是 repr() 的特性,有些人可能会感到困惑——竟然没有查询到真实在内存的值!
因此,想查看更多小数位时,通常使用:format(0.1, ".20f")。
math.isclose():判断两个浮点数是否足够接近
- 使用前,要先
import math,因为isclose()不是 Python 直接内置在全局环境中的函数,而是放在标准库的 math 模块里,而像format()此类则是 python 的内置函数math是模块名isclose是该模块中的函数
- 基本语法:
math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0),一般情况下直接使用默认值时直接输入math.isclose(a, b) - 其类型是 bool 值
- 其中:
- a、b:要比较的两个数
- rel_tol:相对误差容限,默认为
1e-9 - abs_tol:绝对误差容限,默认为
0.0
- 它大致判断: $$ |a-b| \leq \max \left( \text{rel_tol}\times\max(|a|,|b|), \text{abs_tol} \right) $$
- 对于接近零的数,最好设置 abs_tol:
math.isclose(1e-10, 0.0, abs_tol=1e-9),这是因为相对误差在与 0 比较时不太适用。
.hex(): 是浮点数对象的方法,用来把一个 float 显示成精确的十六进制浮点表示。
- 基本语法:
float_value.hex(),前面的值必须是浮点数!否则会SyntaxError: invalid decimal literal - 例如:
x = 0.1
print(x.hex())
0x1.999999999999ap-4
我们可以理解为$1.999999999999a_{16}\times 2^{-4}$,其中:
0x表示十六进制1.999999999999a是十六进制有效数字p-4表示乘以 $2^{-4}$p不是十进制的 $10^n$,而是二进制指数 $2^p$
5.1.3 Trace through the conversion code
自行 trace through 下面的程序,也可以放到 Python Tutor 中观察变量变化:
x = 0.625
# block 1: find power of 2 to make integer
p = 0 # p is power,先进行显示的声明
while ((2**p)*x)%1 != 0:
# %1 is used for grabing the decimal bit(part) of that multiplication only
# e.g. 1.1%1 gives 0.1
print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
p += 1
# 我们将得到如下的运行:
# p = 0: 0.625 * 1 = 0.625,%1 仍不为0
# p = 1: 0.625 * 2 = 1.25,%1 仍不为0
# p = 2: 0.625 * 4 = 2.5,%1 仍不为0
# p = 3: 0.625 * 8 = 5.0,,%1 为0,break
# 这段代码暴露出的问题是,如果没找到合适的 p,那么就会一直跑下去
# block 2: convert to int
num = int(x*(2**p)) # 上一步最后得到的 p 为3,因此乘算后为 5.0,此时要将 5.0 这个浮点数 convert to int 5. 同时使代码保持简洁
# block 3: encode as binary number, same as the previous lecture!
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num//2
# 得到 5 的二进制表示,为 101
# 具体过程就是 5%2,得1,5//2 得2,2%2得0,2//2得1,1%2得1,1//2得0,此时 num == 0,中止循环
# block 4: pad front with 0's (zeros)
# 在字符串前面打上0的标签,为后续做准备,i.e. shift right
for i in range(p - len(result)):
result = '0' + result
# 实际得到 range(3-3), range(0)只循环一次,因此得到了 result = '0101',可以用 repr() 查询
# p=len(result()) 这种是由于 p 的所需的二进制小数点移动位数恰好与二进制的 decimal bit 位数一致,需要补0
# p > len(result()), 这种情况就因为转换成二进制的值位数少于幂,说明实际的数值中是小数点`xx.0000xxx` 才会让p如此大,此时需要从右往左补0(因为原先 while 循环升幂时,必定一开始的 2^p 项无匹配)
# 如果二进制字符串的长度小于需要向左移动的小数位数,就在前面补 `0`。这相当于为后面的“右移”准备足够的位数。
# block 5: insert decimal
result = result[0:-p] + '.' + result[-p:]
# 这里通过 slicing 把小数点插入到倒数第 `p` 位之前
# 由于上述是从右到左进行迭代的,因此 -p 可以表达出逆向编号,例如0101,则0号为0,-3位为1,由此在0和1之间加上小数点
print('The binary representation of the decimal ' + str(x) + ' is ' + str(result))
5.1.4 Why is this a problem?
十进制 0.125 表示:
$$
1\times10^{-1}+2\times10^{-2}+5\times10^{-3}
$$
它在二进制中可以精确表示为: $$ 0.001_2=1\times2^{-3}=0.125 $$
但是十进制的 $0.1_{10}$: $$ 0.1_{10}=1\times10^{-1} $$ 在二进制中却是无限循环的, $0.1_{2}$:
0.0001100110011001100110011...
此类的线形组合是比较难观察出来的。 在执行上述的代码中,下面这些代码显然会进入 infinitily 循环:
x = 0.1
# block 1: find power of 2 to make integer
p = 0
while ((2**p)*x)%1 != 0:
print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
p += 1
其中 0011 会不断重复。计算机的内存不可能存储无限多个 bit,所以只能在某一位停止并进行 rounding(舍入)。
5.1.5 The point?
If everything ultimately is represented in terms of bits (‘cause everything in computer memory is represented in terms of bits, i.e., 0s zeros and 1s ones), we need to think about how to use binary representation to capture numbers.
- Integers are straightforward.
- Real numbers,尤其是带有 decimal point 后数字的数,会产生问题。
- 原本的想法是:把实数乘以某个 2 的幂,使其成为整数,再转换为二进制。
- 但有时根本不存在这样的 2 的幂,且计算机内存无法存下无穷的 bits
- 因此,只能用有限长度的 bit sequence 去近似理论上可能无限长的二进制序列。
5.2 Floats
5.2.1 Storing floating-point numbers #.#
事实上,在计算机的内部存储中,这些实数被拆成两部分来表示。 Floating point is a pair of integers:
- significant digits(有效数字)
- base-2 exponent(二进制指数), the power of 2
- 我们表示浮点数为
#.#,#是整数
可以把它理解成: $$ \text{value}=\text{significant digits}\times2^{\text{exponent}} $$
这里我们来看几个例子:
(1, 1): $$ 1\times2^1 = 10_{2} = 2.0_{10} $$ 可以先写个1.,若第二个数为1,则代表乘以 $2^{1}$,因此我们可以以十进制的角度来看待:这个 (1.1) 对应的实际上就是 $2_{10}$ ;如果从二进制的角度来看,那么 $2^{1}$ 相当于将1.的小数点往右移动一位,因此我们会得到 $10_{2}$。(1, -1): $$ 1\times2^{-1}=1_{10}\times2^{-1}=1_{2}\times2^{-1}=0.1_{2}=0.5 $$(125, -2): $$ 125_{10}\times2^{-2}=125_{10}=1111101_{2}\times2^{-2}=31.25_{10} $$
因为: $$ 125_{10}=1111101_2 $$
把二进制小数点 decimal point 向左移动两位:
$$
1111101_2\times2^{-2}=11111.01_{2}=31.25_{10}
$$
此外,$31.25_{10}$ 我们不仅仅可以是从 $125_{10}\times2^{-2}$ 直接计算得到,也可以是根据 $11111.01_{2}$ 来得到,例如前面的 $11111_{2}$ 对应的十进制 31,后面的 0.01 对应的是十进制的 0.25。
这与十进制科学计数法的思想很接近。例如: $$ 12300=1.23\times10^4 $$
只是 float 使用的指数底数是 2,而不是 10。
快速阅读浮点数:所以简单来看,就是对于浮点数,我们看
[part A].[part B],小数点前的这 Part A 我们将其转化为2进制的表达,随后小数点怎么移动(向左还是向右)、移动几位,则由 Part B 决定。
- 不难体会,called “floating point” object type because location of decimal point can “float” relative to significant digits (有效数字).
#.#向我们揭示了在大多数情况下,计算机将数字(实数)作为整数存储在内存中,而不存储我们认知上的小数(fractions)。
5.2.2 Finite bits represent a potentially infinite sequence
计算机只能使用 a finite set of bits,去表示可能需要无限多 bits 的数:
- 最大有效位数(the maximum number of signifant digitals) 决定了数字表示的 precision(精度);
- most morden computers use 32 bits to represent significant digits;
- 如果一个数的二进制表示超过可用位数(例如上面的 32 bits,32 个 slots ),就必须被 rounded:
- 误差会出现在被截断或舍入的位置
- e.g., error will be at the $32^{nd}$ bit
- 对 32 bits 而言,估计误差的数量级约为 $2\times10^{-10}$(2E-10) 的数量级。因为截断的位置 $2^{-32}$ 大约是 $10^{-10}$。
- 误差会出现在被截断或舍入的位置
需要注意的是,即使误差非常小,它仍然不是零。更重要的是,程序可能会对这些近似值执行大量运算,使误差累积或放大(例如 gmx 中导致的轨迹不一样)。
这里讲义中使用的是便于入门理解的简化模型。Python 通常使用双精度二进制浮点数;本讲的核心不是记住具体 bit layout,而是理解:浮点数的有效位数有限,因此许多数只能近似存储。
- 补充:截止2026年,现代计算机会同时使用 32 位和 64 位浮点数,且现在 64 bits 开始成为默认的主流:
- 32 位浮点数对应 IEEE 754 标准中的单精度(float),而 64 位则对应双精度(double)格式
- 32 位单精度:1 位符号位 + 8 位指数位 + 23 位尾数位
- 64 位单精度:1位符号位 + 11 位指数位 + 52 位尾数位
- 存储空间上,32 位是 4 字节;64 位是 8 字节
- 精度若以有效十进制位数为基准,那么 32 位为 6-7 位,而 64 位为 15-16 位,前者绝对误差约为 $10^{-7}$,后者绝对误差约为 $10^{-16}$
- 32 位常用于图形渲染(所以常见的消费级显卡都是单精度为主),而 64 位常用于科学计算(因此双精度版本的显卡会更贵!),但往往前者运行时效率会更高,因此精度和效率之间会有取舍。
5.2.3 Surprising results
比较下面两个例子。
Exactly representable increment:
x = 0
for i in range(10):
x += 0.125
print(x == 1.25)
True
$0.125=2^{-3}=0.001_{2}$ 可以被有限长度的二进制精确表示,所以重复相加仍能得到精确的 1.25。
Not exactly representable increment:
x = 0
for i in range(10):
x += 0.1
print(x == 1)
print(x, '==', 10*0.1)
False
输出类似:
False
0.9999999999999999 == 1.0
0.1 无法被有限长度的二进制精确表示。每一次 x += 0.1 都是在对一个近似值进行运算,经过多次相加后得到 0.9999999999999999,而不是精确的 1.0。
另一方面,10 * 0.1 只进行了一次乘法与舍入,在这个例子中显示为 1.0。
因此,不同的运算路径可能产生不同的舍入结果。
比较经典的例子,关于 0.1 + 0.2 == 0.3 为 False,但0.1 + 0.3 == 0.4 为 True 的讨论,我们在 第5.1.2.1小节 有进行过深入的讨论。
5.2.4 Moral of the story
由上述的讨论,我们得到的精神就是:
- Never use
==to test floats.- 应该测试两个 float 是否在一个很小的允许距离内。
- 打印出来的内容不一定完整展示内存中实际存储的值
- Careful: 设计使用 float 的算法时必须格外小心
更合理的比较方式是:
abs(a - b) < epsilon
事实上,我们在 第2.2.3节-练习1 中曾经设计过这样的算法。
例如:
x = 0
for i in range(10):
x += 0.1
if abs(x - 1.0) < 0.000001:
print("x is close enough to 1.0")
这里的 epsilon 表示我们允许的误差范围。
5.3 Approximation methods
5.3.1 Review from last lecture
上一讲学习了 guess-and-check:
Guess-and-check provides a simple algorithm for solving problems.
当 potential solutions 的集合是 enumerable(可枚举的)时,exhaustive enumeration 最终一定能够检查完所有候选值
但这种 guess-and-check 方法有明显局限:
- increment 通常是整数,但不一定必须是整数;真正需要的是某种 pattern,让候选值形成一个有限、可枚举的集合。
- 传统 guess-and-check 通常只能告诉我们:找到了精确答案或没有找到精确答案。
- Can’t give us an approximate solution to varying degrees
Better than guess-and-check: 现在的目标不再只是寻找一个精确答案,而是寻找一个近似答案:
- 不仅仅是像 guess-and-check 那样返回“正确答案”;
- 也不仅仅是返回“没有找到答案”;
- 而是返回一个离理想答案足够近的值。
5.3.2 Effect of approximation on algorithms
引入 approximation 后,算法设计会发生变化:
- Exact answer may not be accessible
- 需要寻找“good enough”的答案
- 计算结果只需要 “close enough” to the ideal answer。
- 因为 exhaustive enumeration 不可能测试所有可能的 real values,可能答案的集合其原则上是 infinite
- Floating-point approximation errors 对这种方法非常重要
- can’t rely on equality!!
因此,我们必须明确回答两个问题:
- 什么叫“足够接近”?
- 如何保证循环能够停止,而不是因为跳过目标区间而无限执行?
5.4 Approximating square roots
5.4.1 Finding roots
之前,我们用 exhaustive enumeration / guess-and-check 寻找 perfect square 的整数平方根。
现在希望寻找:
- 任意 positive integer 的平方根;
- 甚至任意 positive number 的平方根。
平方根的数学定义:找到一个 $r$,使 $$ r\times r=x $$
但如果 $x$ 不是 perfect square,通常无法找到一个能被有限表示且精确满足关系的 $r$。若枚举所有实数候选值,搜索空间又是无限的(exhaustive search is infinite)。
所以我们改为寻找一个 approximate square root。
5.4.2 What does “good enough” mean?
寻找一个 $r$,使 $r^2$ 与 $x$ 的距离足够小。 使用 epsilon(一般代表误差):给定 $x$,希望找到 $r$,满足: $$ |r^2-x|<\epsilon $$
这里:
abs(r**2 - x)是当前猜测平方后与目标的距离(取绝对值);epsilon是允许的最大误差,常用 $\epsilon$ 表示;- 当误差小于
epsilon时,就认为答案 good enough。
5.4.3 Approximation algorithm
提出算法如下:
- 从一个已知太小的 guess 开始,称为 $g$。
- 每次增加一个较小的值,称为 $a$,得到新的 guess。
- 检查
g**2是否已经足够接近x,即是否在 $\epsilon$ 允许的范围内。 - 如果还不够接近,继续增加 guess。
- 直到得到足够接近实际答案的值。
实际检查的是: $$ g+k\times a $$
其中 $k$ 为整数。所以它仍然类似 exhaustive enumeration:按照固定 pattern 系统地检查候选值。但由于实数候选集合无限,程序不可能检查所有可能值,只能检查由 increment 生成的一组离散候选值。
5.4.4 Two parameters: epsilon and increment
这个 approximation algorithm 有两个需要设置的参数:
epsilon:how close are we to answer?increment:how much to increase our guess?
Performance will vary based on these values:
- in speed(速度)
- in accuracy(准确度)
Changing the increment:
- 减小
increment:- 会检查更多候选值;
- 程序更慢;
- 但更有可能落入足够接近的区间。
- 增大
increment:- 检查的候选值更少;
- 程序更快;
- 但更容易直接跳过允许误差区间。
Changing epsilon:
- 增大
epsilon:- 接受更大的误差;
- 答案更不准确;
- 但程序更快找到可接受答案。
- 减小
epsilon:- 要求答案更精确;
- 允许区间更窄;
- 程序通常更慢,也更容易被 increment 跳过。
Big Idea
Approximation is like guess-and-check except:
- We increment by some small amount.
- We stop when close enough,因为 exact answer 可能无法得到。
5.4.5 First implementation
x = 36
epsilon = 0.01
num_guesses = 0
guess = 0.0
increment = 0.0001
while abs(guess**2 - x) >= epsilon:
guess += increment
num_guesses += 1
# Will this loop always terminate?
print('num_guesses =', num_guesses)
print(guess, 'is close to square root of', x)
num_guesses = 59992
5.999199999999357 is close to square root of 36
这个代码有非常多的问题,并且可以对比一下我们在 第2.2.3节-练习1 中讨论过的 Newton 法。Newton 法是让用户先给定一个初猜,并且通过解析的方式逐渐迭代 g。而这里,g 是从我们已经写好的硬编码中给定的初猜出发,并且增加的间隔非常的小,这就导致了可能快逼近一个正确答案了(或许我们本来可以得到正确答案),但是由于间隔增加的原因(例如 5.9999,答案在 6.00005,无论怎么加减,间隔只要是0.0001就无法得到正确答案)与浮点数的原因(浮点数误差),很有可能不是精确答案但满足误差的时候就导出答案了。
5.4.6 Observations with different values of x
对于 x = 36:
- 程序没有精确找到
6; - 大约进行了 60,000 次 guesses;
- 但它找到一个平方后距离 36 小于
0.01的值,所以按照算法定义已经 good enough。
Let’s try:
24
2
12345
54321
前几个值可能仍然能停止,但当 x = 54321 时,算法暴露出一个更严重的问题 – 循环没有终止。
5.5 Overshooting epsilon
5.5.1 Trace the large example
x = 54321
epsilon = 0.01
numGuesses = 0
guess = 0.0
increment = 0.0001
while abs(guess**2 - x) >= epsilon:
guess += increment
numGuesses += 1
if numGuesses%100000 == 0:
# 跟踪每 100000 步的计算情况,进行监控和调试
print('Current guess =', guess)
print('Current guess**2 - x =', abs(guess*guess - x))
print('numGuesses =', numGuesses)
print(guess, 'is close to square root of', x)
每进行 100,000 次猜测,就打印一次当前 guess 与误差,便于观察循环是否正在接近答案。不难发现,如果 increment 导致数值在逼近误差容许的范围时,就跨越了这一区域,此后 guess 仍旧 increase,但永远地 abs(guess**2 - x) >= epsilon 为 True,原来的 loop 没有其他停止条件,因此可能永远运行。因此,离正确答案越来越远。

We overshot the epsilon:
这就是 overshoot(越过目标区间)。我们从一个“太小且离目标太远(too far away but too small:前一次 guess**2 仍然太小,并且距离 $x$ 大于 epsilon)”的值,跳到了一个“太大且离目标仍然太远(too far away but too large:下一次 guess**2 已经太大,并且距离 $x$ 仍然大于 epsilon)”的值,中间的可接受区间被直接跳过去。因此有必要修改 loop 逻辑。
5.5.1.1 Oscillation
【脑洞时刻】
- 如果我们设置了超过 epsilon 上限范围,则进行回跳 decreasing;如果仍未达到 epsilon 下限范围,则仍旧 increasing。但如果跳跃的这个范围很大,则有可能一跳,increasing -> 越过了上限;一跳,decreasing -> 低于下限,因此出现了振荡(oscillation),如此也会导致无限循环。
- 如果我们设置的步长能够根据前一步的大小进行动态调整,那么就可以达到收敛。但仍旧有个问题,如果步长只根据方向动态调整时,其调整刚好落到了上述的共轭情况,本质上仍然是固定幅度的来回跳动,也可能进入周期循环。
例如,目标平方根在两个猜测值之间:
guess = 233.06 → guess**2 太小
guess = 233.07 → guess**2 太大
如果步长始终固定为 0.01,程序就可能不断地:
233.06 → 233.07 → 233.06 → 233.07 → ...
ai 认为,要保证逐渐收敛,需要增加一条新规则:
- 每次越过目标、改变方向时,都将步长缩小,例如减半。这样,即使程序仍然左右来回跳动,跳动幅度也会越来越小。
- 虽然仍存在振荡,但这是一个衰减振荡,步长逐渐趋近于零,因此不会永远维持同样幅度的循环,最终有望进入 epsilon 允许的范围。
- 这种方法算是带有方向反转和步长缩减的自适应搜索,非常接近后面的 bisection search(二分搜索法)。而像机器学习的损失函数 ($\text{L}(\boldsymbol{\theta})$) 或 Newton 法,则是 gradient descent 的方法。
下面我们来实现上述这个想法的算法:
x = 54321
epsilon = 0.01
numGuesses = 0
guess = 0.0
# 初始步长可以设得较大,从而避免从 0 开始进行数百万次尝试
increment = 1.0
# direction = 1 表示 increasing
# direction = -1 表示 decreasing、
# 这实际上也类似于设置 boolean flag
direction = 1
# 防止程序因意外逻辑错误而永远运行
maxIterations = 1000000
while abs(guess**2 - x) >= epsilon and numGuesses < maxIterations:
# 根据当前方向增加或减小 guess
guess += direction * increment
numGuesses += 1
# 迭代次数监督器
# 当前 guess 太大,并且之前正在增加
# 说明刚刚越过了目标
if guess**2 > x and direction == 1:
direction = -1
increment /= 2
# 当前 guess 太小,并且之前正在减小
# 说明从另一侧再次越过了目标
elif guess**2 < x and direction == -1:
direction = 1
increment /= 2 # tips: 除了 +=,也可以 *= 和 /=
print('numGuesses =', numGuesses) # 进行监测
if abs(guess**2 - x) < epsilon:
print(guess, 'is close to square root of', x)
print('error =', abs(guess**2 - x))
else:
print('Failed to find an answer within the iteration limit.')
届时,返回如下:
numGuesses = 257
233.06866455078125 is close to square root of 54321
error = 0.00239548459649086
这也揭示了这种算法可以很大幅度地减少计算的步数!
5.5.2 Fix: add another end condition
修正版:
x = 54321
epsilon = 0.01
numGuesses = 0
guess = 0.0
increment = 0.0001
while abs(guess**2 - x) >= epsilon and guess**2 <= x:
guess += increment
numGuesses += 1
print('numGuesses =', numGuesses)
if abs(guess**2 - x) >= epsilon:
print('Failed on square root of', x)
else:
print(guess, 'is close to square root of', x)
因此,只要发生以下任一情况,loop 都会停止:
- 已经足够接近;
guess**2已经超过x。
Detect success or failure: 循环停止并不必然表示成功。因此退出循环后一般需要打印信息辅佐我们进行判断。
loop termination(循环终止)与 algorithm success(算法成功)不是同一个概念。
如果将上述步长改为 increment = 0.00001,则更小的步长使候选值更密集,更有机会落入 epsilon 区间;但问题是我们仍要进行试错,因为我们事先不知道多小的步长合适,并且越小的步长在此例中会导致计算冗余。
显然,这个解决办法远不及我们在 第5.5.1.1小节 提出的改进好。我们不仅优化了算法,更快(一开始步长能够很大)更准(后面步长自动搜索调整),并且还增添了步数的检测器,便于进一步监测。
Big Idea
It is possible to overshoot the epsilon, so you need another end condition.
Be careful when comparing floats.
5.6 Lessons learned in approximation
- 不能使用
==检查 float 算法的 exit condition。 - Need to be careful that looping mechanism doesn’t jump over exit test and loop forever
- Tradeoff(利弊权衡) exists between efficiency of algorithm and accuracy of result
- Need to think about how close an answer we want when setting parameters of algorithm
- 使用很小的 increment 得到好答案时,这种方法可能 painfully slow。
- 是否存在一种仍然能得到 good answer、但速度更快的方法?
- YES! We will see it next lecture.(前面的【头脑风暴】中已经给出我的 version)
5.7 Summary
- Floating-point numbers introduce challenges.
- 它们无法总是在内存中被精确表示。
- Operations on floats introduce tiny errors.
- Multiple operations on floats can magnify errors.
- Approximation methods use floats。
- Approximation 类似于 guess-and-check,但:
- 使用 float 作为 increment;
- 在 close enough 时停止,而不是必须找到精确相等的答案。
- 最好不要在 stopping condition 中使用
==比较 floats。 - 要小心 overshooting the close-enough stopping condition。
5.8 Professional supplement: numerical concepts behind Lecture 5
5.8.1 Absolute error(绝对误差)
本讲使用的:
abs(guess**2 - x)
就是 absolute error 的形式: $$ \text{absolute error}=|\text{approximation}-\text{target}| $$ 它直接衡量近似值与目标值之间相差多少。
但 absolute error 是否足够小,有时取决于目标数的尺度。例如误差 0.01:
- 对目标
1来说可能较大; - 对目标
1,000,000来说可能已经非常小。
5.8.2 Relative error(相对误差)
为了考虑尺度,可以使用 relative error: $$ \text{relative error}=\frac{|\text{approximation}-\text{target}|}{|\text{target}|} $$
例如:
abs(guess**2 - x) / abs(x) < epsilon
相对误差描述的是“误差占目标值的比例”。在科学计算中,absolute tolerance 与 relative tolerance 经常结合使用。
5.8.3 Tolerance(容差)
epsilon 在数值算法中通常也叫:
- tolerance
- error tolerance
- absolute tolerance
它不是“真实误差本身”,而是程序员规定的可接受误差上限。
5.8.4 Discretization(离散化)
真实数轴上有无限多个候选值,但程序只检查:
$$ g,g+a,g+2a,g+3a,\ldots $$
这相当于把连续搜索空间切成固定间距的离散点,称为 discretization(离散化)。
increment 就是离散网格的 spacing:
- spacing 大:计算快,但分辨率低;
- spacing 小:分辨率高,但计算慢。
Overshoot 的根本原因之一,就是离散点之间的间距大于可接受区间的宽度。
5.8.5 Accumulated rounding error(累积舍入误差)
下面两种写法在数学上看似相同:
x = 0
for i in range(10):
x += 0.1
x = 10 * 0.1
但第一种执行多次浮点加法,每一步都可能发生舍入;第二种只经历一次主要运算与舍入。因此,运算顺序和运算次数会影响最终结果。这种现象可以称为 accumulated rounding error。
5.8.6 math.isclose()
在实际 Python 程序中,可以使用标准库提供的 math.isclose() 比较浮点数,并返回 boolean。我们在 第5.1.2.1小节 曾经介绍过。
import math
x = 0
for i in range(10):
x += 0.1
print(math.isclose(x, 1.0))
它会同时考虑 relative tolerance 和 absolute tolerance,比只写一个固定的 abs(a-b) < epsilon 更适合通用浮点比较。不过在本讲阶段,手动写 abs(a-b) < epsilon 更有助于理解近似算法的基本逻辑。
5.8.7 Summary of extra terms
| 术语 | 含义 |
|---|---|
| significand | 浮点表示中的有效数字部分 |
| exponent | 控制二进制小数点位置的指数部分 |
| rounding error | 因有限位数舍入而产生的误差 |
| absolute error | 近似值与目标值之差的绝对值 |
| relative error | 绝对误差相对于目标值大小的比例 |
| tolerance | 算法允许的误差上限 |
| discretization | 把连续候选空间转成离散候选点 |
| overshoot | 一次更新直接跳过允许误差区间 |
| accumulated error | 多次运算后逐步累积或放大的误差 |
| termination condition | 决定循环何时结束的条件 |
Lecture 6: Bisection Search
这一讲从上一讲的 approximation methods(近似方法) 出发,介绍一种能够显著减少猜测次数的算法:bisection search(二分搜索)。本讲后半还会介绍另一种生成近似解的方法 Newton–Raphson,并引出 decomposition 和 abstraction。
6.1 Last lecture:浮点数与近似方法
浮点数的二进制表示可能并不精确,浮点运算会引入 tiny errors,多次运算还可能放大误差。因此,对于近似结果不应依赖 ==,而应检查误差是否落在 epsilon 所规定的容许范围内。
6.1.1 Recap:用 approximation method 求平方根
下面是上一讲中求 $54321$ 平方根的近似算法:
x = 54321
epsilon = 0.01
num_guesses = 0
guess = 0.0
increment = 0.0001
while abs(guess**2 - x) >= epsilon and guess**2 <= x:
guess += increment
num_guesses += 1
print('num_guesses =', num_guesses)
if abs(guess**2 - x) >= epsilon:
print('Failed on square root of', x)
else:
print(guess, 'is close to square root of', x)
这里的 stopping condition 同时要求误差仍大于等于 epsilon,并且 guess**2 还没有超过 x。
- increment 太大:相邻两个 guess 之间的间隔可能大于允许误差区间,直接跨过 “close enough” 的答案。
- increment 太小:更可能找到满足误差要求的值,却需要极多次循环。
这说明近似算法的关键不只在于如何检查答案,还在于如何更聪明地 generate guesses。
6.2 Bisection search
6.2.1 Chance to win big bucks
- Suppose I attach a hundred dollar bill to a particular page in the text book, 448 pages long
- If you can guess page in 8 or fewer guesses, you get big bucks
- If you fail, you get an F
- Would you want to play?
YOU CHANCES ARE ABOUT 1 IN 56.
- Now suppose on each guess I told you whether you were correct, or too low or too high
- Would you want to play in this case?
YOU CHANCES ARE ABOUT 1 IN 3.
只有 “correct / incorrect” 反馈时,一次错误猜测只能排除当前这一页;如果还能得到 “too low / too high” 的方向反馈,就可以每次排除一半页面。
- 因为 $2^8=256<448<512=2^9$,若严格保证找出 448 页中的任意一页,最坏情况需要 9 次 midpoint guesses;“8 次以内获胜”并不能覆盖所有页面。
- 核心观点就是二分法 bisection,计算复杂度的时候从 $2^n$ 脑测即可。
6.2.2 Basic idea
- Apply it to problems with an inherent order to the range of possible answers
- Suppose we know answer lies within some interval
- Guess midpoint of interval
- If not the answer, check if answer is greater than or less than midpoint
- Change interval
- Repeat
- Process cuts set of things to check in half (切对半并检查) at each stage
- 穷举和二分法的区别:
- Exhaustive search reduces them from N to N-1 on each step
- Bisection search reduces them from N to N/2 on each step
二分搜索是一种可以用来解决某种排序问题的方法,并且假设我们知道其答案的区间(interval)。
二分搜索利用候选答案的 inherent order(内在顺序)。已知答案在区间 [low, high] 中时,先猜中点 midpoint;再根据反馈舍弃前半或后半区间,重复上述过程。
6.2.3 Log growth is better
- Process cuts set of things to check in half at each stage
- Characteristic of a logarithmic growth(对数增长)
- 而像前面的逐个 guess-and-check 的方法是 线性增长的,linear growth
- 后续的内容中我们将讨论不同算法的 cost 以及增长的特点,并讨论一个算法比另一个算法来得更高效这意味着什么。
- Algorithm comparison: guess-and-check vs. bisection search
- Checking answer on-by-one iteratively is linear in the number of possible guesses
- Checking answer by guessing the halfway point is logarithmic on the number of possible guesses
- Log algorithm is much more efficient
事实上,二分搜索不仅仅用在处理数字上,还可以处理任何有顺序属性的事物。 例如,如果全班按姓名的字母顺序从前到后坐好,要寻找某位同学,就可以先询问教室中间的人;根据姓名顺序排除前一半或后一半,再重复这个过程。
6.2.4 Bisection search for square root
假设平方根在 0 和 x 之间,令中点为 g:
- 如果
g**2已经足够接近x,停止。 - 如果
g**2 > x,则g太大,下一次只搜索0到g。 - 如果新猜测满足
g**2 < x,则g太小,下一次只搜索g到原来的上界。 - At each stage, reduce range of values to search by half.

Big Idea
Bisection search takes advantage of properties of the problem.
- The search space has an order. (牢记有顺序性的特点!)
- feedback: We can tell whether the guess was too low or too high.(可以对得到的结果分辨其是高还是低)
仅仅“候选答案是数字”并不足以使用二分;还必须有顺序,并且每次反馈都能告诉我们应保留哪一侧。
6.2.5 You Try It:4-digit PIN code
You are guessing a 4 digit pin code. The only feedback the phone tells you is whether your guess is correct or not. Can you use bisection search to quickly and correctly guess the code?
不能。PIN 虽然可按数值排序,但手机只反馈 correct / incorrect,错误时没有 “too low / too high” 的方向信息,因而不能安全地排除一半候选项。
6.2.6 You Try It:任意精度小数
You are playing an EXTREME guessing game to guess a number EXACTLY. A friend has a decimal number between 0 and 10 (to any precision) in mind. The feedback on your guess is whether it is correct, too high, or too low. Can you use bisection search to quickly and correctly guess the number?
如果要求在有限次数内 EXACTLY 猜出任意精度实数,则不能保证做到:区间中有无限多个候选数。二分可以不断缩小区间,但通常需要用 epsilon 把目标改为 “close enough”,才能给出可实际终止的条件。如果这时候猜数对应的实数是 pi,则不能拿到精确的值。
虽然使用 bisection search,若不设置一个 epsilon,则将会成为一个 infinite algorithm,不会终止。
6.3 从慢速近似到快速平方根
6.3.1 Slow square root using approximation methods
x = 54321
epsilon = 0.01
num_guesses = 0
guess = 0.0
increment = 0.00001
while abs(guess**2 - x) >= epsilon and guess**2 <= x:
guess += increment
num_guesses += 1
print('num_guesses =', num_guesses)
if abs(guess**2 - x) >= epsilon:
print('Failed on square root of', x)
else:
print(guess, 'is close to square root of', x)
这个 brute force approximation 需要超过 23 million guesses。
6.3.2 Fast square root:逐步构造代码
首先确定端点并计算中点:
x = 54321
epsilon = 0.01
num_guesses = 0
# initialize some stuff
low = 0
high = x
guess = (high + low)/2.0
循环中利用方向反馈更新上下界:
while abs(guess**2 - x) >= epsilon:
# reset the low/high endpoint to the guess
if guess**2 < x:
low = guess
else:
high = guess
# update the value of guess
guess = (high + low)/2.0
num_guesses += 1
讲义中的完整代码为:
x = 54321
epsilon = 0.01
num_guesses = 0
low = 0
high = x
guess = (high + low)/2.0
while abs(guess**2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
num_guesses += 1
print('num_guesses =', num_guesses)
print(guess, 'is close to square root of', x)
输出中 num_guesses 为 30。相比逐个增加 0.00001,二分搜索 radically reduces computation time。
6.3.3 Why logarithmic growth?
- Brute force search for root of 54321 took over 23M guesses
- With bisection search, reduced to 30 guesses!
- Brute force method is linear in size of problem, because number of steps grows linearly as we increase problem size
- Bisection search is logarithmic in size of problem, because number of steps grows logarithmically with problem size
搜索空间 (search space) 依次变为: 这里 N 可以指抽象上的搜索空间。
- first guess: $N/2$
- second guess: $N/4$
- $k^{th}$ guess: $N/2^k$
当只剩一个候选量级时: $$ \frac{N}{2^k}=1 $$ 所以: $$ N=2^k,\qquad k=\log_2N $$ 这意味着搜索空间被分成了 $2^{k}$,说明算法会指引我们并收敛(converge)到第 $\log_{2}N$ 的猜数。
- guess converges on the order of $\log_{2}N$ steps using bisection search,所以才称之为 logarithmic p.s. 这里的对数底数为 2。在 Big-O 表示中,常数底数不会改变复杂度类别,因此往往也直接写复杂度为 $log(N)$
So:
It takes us k steps to guess using bisection search == It takes us log(N) steps to guess using bisection search
6.4 Does bisection search always work?
6.4.1 当 0 < x < 1
- If
x < 1, we are searching from0tox. - But know square root is greater than
xand less than1. - Modify the code to choose the search space depending on value of
x.
!!小心这种情况!!
例如 $x=0.5$ 时,因为 $\sqrt{0.5}$ 约为 0.7071 ,所以$\sqrt{0.5}>0.5$。若仍把上界设为 x (上例中我们就是选取 guess 的范围是 0 到 x 的 midpoint 为初猜),x 真正的平方根根本不在搜索区间内。因此结果就是下界逐渐增大 x 变为 0.5,最后 low = 0.5,high = 0.5,等于以 x 为上界的值,于是无限循环。
所以设置二分法,得考虑好是否真的覆盖到了搜索区间。
6.4.1.1 You Try It:补全搜索边界
核心思路就是补全端点。
x = 0.5
epsilon = 0.01
# 当 x 属于 0 到 1 的时候,x 的平方根必然是属于 0 到 1 且大于 x 的,因此这时候得分类讨论并改端点
if x >= 1:
low = 1.0
high = x
else:
low = x
high = 1.0
guess = (high + low)/2
while abs(guess**2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
print(f'{str(guess)} is close to square root of {str(x)}')
这段讲义代码处理所有 positive x:当 x >= 1 时,平方根位于 [1, x];当 0 < x < 1 时,平方根位于 [x, 1]。x = 0 可直接返回 0;而负数在实数范围内没有平方根,因此不能直接使用这段代码。
事实上,如果当 0<x<1,直接设为 low = 0 high = 1 也顶多循环一次,从 0.5 到 1 的正确范围里继续搜索,不影响结论。
6.4.2 Some observations
- Bisection search radically reduces computation time – being smart about generating guesses is important
- Search space gets smaller quickly at the beginning and then more slowly (in absolute terms, but not as a fraction of search space,这里以绝对值来计算的,而非指相对于搜索空间的占比情况:一开始搜索从快,到后续很慢慢) later
- Works on problems with “ordering” property(需要与排序属性相关)
区间每次始终缩小为原来的一半;只是随着区间本身变小,每次减少的绝对长度也随之变小。
6.4.3 You Try It:正数的立方根
Write code to do bisection search to find the cube root of positive cubes within some epsilon. Start with:
cube = 27
epsilon = 0.01
low = 0
high = cube
完整解法:
cube = 27
epsilon = 0.01
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsilon:
if guess**3 < cube:
low = guess
else:
high = guess
guess = (high + low)/2.0
print(guess, 'is close to the cube root of', cube)
由于 $g^3$ 在实数范围内单调递增,所以 “too low / too high” 反馈能够正确决定更新哪一侧。
若扩展到负数,需选择能够 bracket 负立方根的端点,例如 low = cube, high = 0。
6.5 Newton–Raphson
6.5.1 General idea
- General approximation algorithm to find roots of a polynomial in one variable
- 不断求导降阶 $$ p(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots+a_1x+a_0 $$
- Newton and Raphson showed that if
gis an approximation to the root, then $$ g-\frac{p(g)}{p’(g)} $$ is a better approximation; where $p’$ is derivative of $p$. - For example, to find the square root of 24, find the root of $p(x)=x^2-24$.
如下图的直观认识,先代入 x1 求其切线与 x 轴即 y 为 0 时的交点为 x2,然后再代入 x2 求切线,然后再找切线交点,如此循环得到更理想的近似的 guess。

6.5.2 Newton–Raphson root finder
对于 $x^2-k$:
- Simple case for a polynomial: $x^2-k$
- First derivative: $2x$
- Given a guess
gfor root ofk, a better guess is: $$ g-\frac{g^2-k}{2g} $$ - This eventually finds an approximation to the square root of
k!
讲义代码:
epsilon = 0.01
k = 24.0
guess = k/2.0
num_guesses = 0
while abs(guess*guess - k) >= epsilon:
num_guesses += 1
guess = guess - (((guess**2) - k)/(2*guess))
print('num_guesses = ' + str(num_guesses))
print('Square root of ' + str(k) + ' is about ' + str(guess))
Newton–Raphson 是另一种生成 guess 的高效方法。不过它不像 bracketed bisection 那样始终保留一个包住解的区间(不能给出解集所在的区间);初值、导数为零等因素可能影响它是否收敛。
6.6 Iterative algorithms
迭代算法的特点:
- Guess and check methods build on reusing same code
- Use a looping construct
- Generate guesses (important difference in algorithms)
- Check and continue
- Generating guesses
- Exhaustive enumeration
- Approximation algorithm
- Bisection search
- Newton–Raphson (for root finding)
这些算法的共同结构是:使用 loop 反复生成猜测、检查猜测,并决定是否继续;它们最重要的差别之一是 如何生成下一次猜测。
6.7 Summary
- For many problems, cannot find exact answer
- Need to seek a “good enough” answer using approximations
- When testing floating point numbers
- It’s important to understand how the computer represents these in binary
- Understand why we use “close enough” and not
==
- Bisection search is FAST but for problems with:
- Two endpoints
- An ordering to the values
- Feedback on guesses (too low, too high, correct, etc.)
- Newton–Raphson is a smart way to find roots of a polynomial
6.8 Intro: Decomposition and abstraction
到目前为止,我们学习了 primitives、complex expressions、branching 和 iteration;学习了 expressions、variables、conditions、loops。 原则上,这些基本语言机制已经足以描述任何可计算过程,但要创建易于修改、维护和理解的程序,还需要两个重要概念(这两个概念在所有现代编程语言中都存在):
Decomposition:How to divide a program into self-contained parts that can be combined to solve the current problem. (其实我们将逐渐发掘 python 得胶水语言的本质)
Abstraction:How to ignore unnecessary detail.
Decomposition 的理想目标是:
- Ideally parts can be reused by other programs
- Self-contained means parts should complete computation using only inputs provided to them and “basic” operations。
例如把:
a = 3.14*2.2*2.2
分解成更能表达含义的绑定:
pi = 3.14
r = 2.2
area = pi*r**2
- Abstraction:
- Used to separate what something does, from how it actually does it(先不关心具体怎么做,而先关心是做什么的目的)
- reating parts and abstracting away details allows us to write complex code while suppressing (隐瞒、封锁、压抑、省略) details, so that we are not overwhelmed by that complexity。创建部件并隐藏细节,使我们能够编写复杂程序而不被所有底层细节淹没。
例如在上述的代码加上:
# calculate the area of a circle
Big Idea
Make code easy to
- create
- modify
- maintain
- understand
6.9 Supplement:After lecture 6
本节为讲义后的专业补充
6.9.1 Discrete binary search vs. numerical bisection
这里我们将引入离散二分搜索和数值二分法的概念。
| 概念 | Discrete binary search | Numerical bisection |
|---|---|---|
| 候选空间 | 有序的离散元素 | 连续区间 |
| 目标 | 找到元素或插入位置 | 近似求根或满足阈值的位置 |
| 终止方式 | 候选耗尽或命中 | 函数残差或区间宽度小于 tolerance |
| 复杂度 | $O(\log N)$ | 约 $\log_2((b-a)/\delta)$ 次将区间缩至宽度 $\delta$ |
数值二分通常针对连续函数 $f$ 求 $f(x)=0$。若 f(low) 与 f(high) 异号,并且函数在该区间连续,就能保证区间中至少有一个根;每次通过符号判断保留仍然 bracket 根的半区间。
6.9.2 Interval invariant、monotonicity 与 convergence 术语
- Search space:当前仍可能包含答案的候选范围。
- Interval invariant:每次迭代前后都保持“目标仍在
[low, high]中”。这正是更新边界时需要维护的 loop invariant。 - Monotonicity(单调性):平方函数在非负区间单调递增,所以
guess**2 < x能推出 guess 太小。对非单调函数,不能仅凭大小照搬这套更新规则。 - Convergence(收敛):二分每次把区间宽度减半,因此只要终止条件合理,就会逐步逼近目标。
6.9.3 Absolute error、relative error 与停止条件
abs(guess**2 - x) < epsilon 控制的是函数值的 absolute error。
固定 absolute tolerance 对数量级差异很大的问题未必合适;relative error 会相对于目标尺度衡量误差。
前面我们已经讲述过:
import math
print(math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9, abs_tol=1e-12))
math.isclose() 同时提供 relative tolerance 和 absolute tolerance,适合比较两个浮点结果。
不过在实际 bisection 中,应该得考虑这几点:
- 选取绝对误差还是相对误差
- 区间宽度停止条件,并设置最大迭代次数,避免输入不满足前提时无限循环
6.9.4 ML 与计算化学中的联系
- Classification threshold:若评价目标随阈值呈可利用的单调关系,可以二分寻找满足某一约束的阈值;但 Accuracy、F1 等指标未必随阈值单调,不能自动套用二分。
- Monotonic parameter search:寻找使单调标量函数达到目标的参数时,适合先 bracketing,再二分细化。
- Learning-rate refinement:只有当判据相对于 learning rate 具有可靠的方向性与单调性时,局部范围细化才类似二分;一般 hyperparameter optimization 并不天然是 bisection problem。
- Scientific root finding:状态方程、守恒条件或校准方程若能写成连续标量方程 $f(x)=0$,可以先找异号端点,再用二分稳健求根。
- Potential-energy surface:多维势能面优化涉及许多坐标、非单调结构和局部极小值,并不是一维二分问题。二分可用于其中某个已 bracket 且具方向信息的一维子问题。
- Bisection vs. Newton:bracketing bisection 通常更稳健但收敛较慢;Newton’s method 利用导数,接近解时可能更快,却依赖合适初值和良好的导数。科学计算中常组合稳健 bracket 与更快的 derivative-based update。
Lecture 7: Decomposition, Abstraction, and Functions
7.1 Smartphone:black-box analogy
智能手机可以被视为一个 black box(黑箱):
- Its inputs
- Its outputs
- How outputs are related to inputs, without any knowledge of its internal workings
- Implementation is “opaque” (or black)
7.1.1 Abstraction
- User doesn’t know the details of how it works
- We don’t need to know how something works in order to know how to use it
- User does know the interface
- Device converts a sequence of screen touches and sounds into expected useful functionality
- Know relationship between input and output
我们只关注 interface! 用户只需掌握 interface(接口)以及 input 与 output 的关系,无需了解所有内部实现。
7.1.2 Abstraction enables decomposition
手机基本上抽象掉了所有硬件的细节和实现。
Abstraction enables decomposition. 一旦 abstract away details,我们就可以让不同的制造商负责不同的组件(这个就是 decomposition),且之后以某种方式将这些部件重新组合在一起。
- 100’s of distinct parts
- Designed and made by different companies
- Do not communicate with each other, other than specifications for components
- May use same subparts as others
- 他们怎么知道自己正在开发的东西确实能和其他的组件进行匹配?—— 利用 decompostion
- Each component maker has to know how its component interfaces to other components (知道接口或者遵循某种规格 specification 的输入或输出,所以接口会 standardized)
- Each component maker can solve sub-problems independent of other parts, so long as they provide specified inputs
- True for hardware and for software
Big Idea
Apply abstraction (black box) and decomposition (split into self-contained parts) to programming!
7.2 Suppress details with abstraction
- In programming, want to think of piece of code as black box
- Hide tedious coding details from the user
- Reuse black box at different parts in the code (no copy/pasting!)
- Coder creates details, and designs interface
- User does not need or want to see details
程序员通过 function(函数,也称 procedure 过程) 实现 abstraction。我们之前在 tcl 语言中也介绍过控制流和函数(过程)了。
我们已经使用过许多函数:
max(1, 4) # 返回这两个输入中的最大值,事实上 1 和 4 可以在前一步被赋值
abs(-3) # 计算绝对值
len("mom's spaghetti") # 计算字符串的长度,包括空格!
A function lets us capture code within a black box. Once we create function, it will produce an output from inputs, while hiding details of how it does the computation.
7.2.1 Docstring as a specification
- A function has specifications, captured using docstrings.
- docstring: the docstring at the beginning of the function clearly explains its purpose and usage. 翻译为文档字符串,一般出现在函数、类、文件、包定义顶部时的一个字符串,用于记录接口,解释需要传递什么参数给这个函数。
- Think of a docstring as “contract” between coder and user:
- If user provides input that satisfies stated conditions, function will produce output according to specs, including indicated side effects.
- Not typically enforced in Python (we’ll see assertions later), but user relies on coder’s work satisfying the contract.
由于我们将函数比喻成 contract 合同,因此会后续衍生出 signature 的概念。
因此这里有很多小细节:
- docstring
- signature
- specification
Docstring 描述合法输入、返回结果以及 side effects(副作用)。它是 specification,而不是 Python 自动强制执行的输入检查。所以很大程度上完全取决于写代码的人能确保他们的 specification 足够的详细。
事实上,当我们在文本编辑器中悬停在某个函数上的时候,就会有个小文本框弹出,其中会揭示其规范或文档字符串,也叫做函数的签名(signature):

7.3 Create structure with decomposition
有了这些不同的 function,我们可以将 large file of code 拆分成多个模块 (module) 或者是一个函数的内容。你可以使用这些函数将大片程序代码分解成更小 self-contained modules,每个模块给出不同的 output,然后组合封包给 function 作为 input,进而执行 procedure。
- Given the idea of black box abstraction, use it to divide code into modules that are:
- Self-contained
- Intended to be reusable
- Modules are used to:
- Break up code into logical pieces
- Keep code organized
- Keep code coherent (readable and understandable)
- In this lecture, achieve decomposition with functions
- In a few lectures, achieve decomposition with classes 【lecture 17】
- Decomposition relies on abstraction to enable construction of complex modules from simpler ones
7.4 Functions
- Reusable pieces of code, called functions or procedures
- Capture steps of a computation so that we can use with any input
- A function is just some code written in a special, reusable way (只是以一种特殊的方式重新使用前面我们学过的那些基础来写而已)
以往,我们代码是 line by line, top to bottom。 不过现在我们定义了函数,小块的函数可以在我们的代码中多次复用。
7.4.1 Definition vs. invocation
invocate, invocation: 调用
- Defining a function tells Python some code now exists in memory. 告诉 python 这个 module 或 function 存在于我们的程序中
- Functions are only useful when they are run (“called” or “invoked”).
- 没错!你经常遇到的一些程序异常经常提醒的 called 和 invoked 就是来源于此!
- 不调用则不执行
- You write a function once but can run it many times!
- Compare to code in a file:
- It doesn’t run when you load the file.
- It runs when you hit the run button.
执行 def 会创建 function object,并把函数名绑定到它;函数体不会因此立即运行。只有调用(call / invoke)函数时,函数体才执行。
7.4.2 Function characteristics
【重点!】
- Has a name
- (think: variable bound to a function object)
- Has (formal) parameters (0 or more,以前我们在 tcl 语言中学到过如何设置默认)
- The inputs
- Has a docstring (optional but recommended)
- A comment delineated by
"""(triple quotes) that provides a specification for the function – contract relating output to input - 这只是个 multi-line commen 多行注释,去告诉用此函数的人输入的内容、函数的作用,以及返回什么
- 类似于 markdown 语法中的
```,得 begin 和 end 的时候加上符号才行
- A comment delineated by
- Has a body, a set of instructions to execute when function is called
- 一般而言咱们函数的主体就是执行 python 代码;事实上我们前面学到过的一切东西都可以被封装(wrapped)到一个函数中
- Returns something
- 函数必须在某个时刻结束,且返回一个有意义的值说明任务的结果
- Keyword
return
7.4.3 How to write a function
一个简单的 is_even 函数的例子:
# 注意 identation
# def is keyword, don't forget the colon!
# def func_name(arg):
def is_even(i):
# 这里开始 docstring
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
# 开始 body
if i%2 == 0:
# give something back!
return True
else:
return False

几点注意:
- standard:
def和()parentheses,以及:colon def之后的func_name和arg是你可以自行决定的- 可以是 parameters(形参) 也可以是 args(实参)。关于此类区别,我们在 tcl 语言中也讲过了
- 如果没有参数,你也可以什么
arg都不用写 - 如果
arg超过一个,可以用逗号隔开,例如arg1,arg2, ... - 函数的内容必须和前面的分支一样,得有 identation
- 在这里你可以抉择是适当的将某些内容打印到控制台 (用
print())还是 return a value to the user - 这些代码不会被 invoked (called),只是用于声明这段代码存在着某个名为
is_even的 function object(函数对象)
写函数时先回答:
- What is the problem?
给定一个 int
i,判断它是否为偶数;据此写函数名和 specs。 - How to solve the problem? 检查除以 2 的余数是否为 0,并思考需要返回什么 value。
- Can you make the code cleaner?
例如,
i%2 == 0本身已经求值得到 Boolean。
因此可简化为:
def is_even(i):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
return i%2 == 0
Big Idea
At this point, all we’ve done is make a function object.
7.4.4 How to call (invoke) a function
# Name_of_the_function(value_for_parameters_of_the_function)
is_even(3)
is_even(8)
# 值会立马返回给调用它的地方
这两行分别 invocate is_even;但在普通脚本中,如果没有 print、赋值或其他使用返回值的操作,结果不会自动显示,而是隐式地得到。
注意:无论返回的值是什么,那个值会立即返回给调用它的地方;这意味着 that return value will completely replace that function call。因为是 function object,因此类似于运算符的表达,当评估出结果后,将整个表达式——例如上面的
is_even(3)直接对应值为False。 functions 类似于 python 中的表达式,只不过它是一组被评估的代码行;若函数只返回了一个值,则那个值将代替其对应的整个函数的调用
即后续 is_even(3) 的 function call 在经过 evaluated 后将被替换为 False。
一个文件中可以同时包含定义与调用:
# definition
def is_even(i):
return i%2 == 0
# func call
is_even(3)
7.5 What happens when you call a function?
在调用之前,定义函数的字段默默地存储在内存中。
以 is_even(3) 为例:
- Python 将 function definition 中的 formal parameter(形参)
i绑定到 function call 提供的 actual argument3 - Python 执行函数体中的 expressions,body 内容,也就是计算
return 3%2 == 0 - 当 python 得到返回值时,立刻退出函数
return把结果False交回调用处,整个 function call expression 被其 return value 取代
>>> def is_even(i):
... return i%2 == 0
...
>>> is_even(3)
False
>>> print(is_even(3))
False
第二次调用位于 print() 的 argument 位置,因此先得到 False,再由 print 将其显示出来。
print 的意义就是打印出函数调用出来的结果用于监测。
Big Idea
A function’s code only runs when you call (aka invoke) the function.
7.5.1 You Try It:div_by
Write code that satisfies the following specs (specifications)
def div_by(n, d):
""" n and d are ints > 0
Returns True if d divides n evenly and False otherwise """
Test your code with:
n = 10andd = 3n = 195andd = 13
My work:
def div_by(n, d):
return (n/d)%2 == 0
解法:
def div_by(n, d):
""" n and d are ints > 0
Returns True if d divides n evenly and False otherwise """
return n%d == 0
print(div_by(10, 3)) # False
print(div_by(195, 13)) # True
这里其实出现了我在业务理解上的错误,我的理解是返回能被偶数地整除则返回 True,但事实上题目 evenly 这里是平均地,并非偶数地意思,因此只要能被整除——所以直接取模即可。
但如果输入的是如下:
def div_by(n, d):
if n%d == 0:
print(True)
else:
print(False)
>>> div_by(9, 3)
True
>>> x = div_by(9,3)
True
>>> print(x)
None
则会打印出 True 或 False,但看后台记录可以发现还返回了个 None。
事实上,print ≠ return。
如果一个函数执行结束,没有遇到 return xxx,那么 Python 自动执行 return None。因此,上面的例子 div_by(9,3) 这个函数对象由于没有设置 return 的返回值,因此整个函数对象映射为 None,而之所以一开始能得到 True,纯粹是等式右侧先进行评估,function call 的时候顺带打印了出来。
The function call is replaced with the return value! 如果函数里没有
returnstatement,则 python 会自动返回这个特殊的None
7.6 Program scope and function calls
下面让我们 zoom out(放大)一下,来谈谈函数是如何在内存中存储的。
7.6.1 Zooming out
当创建变量的时候,发生了什么?
没有函数时,名字都直接出现在 program scope(程序作用域),此时可以将其视为内存中放了(抽象来说是程序作用域中) a、b、c 分别绑定到 3、4、7。:
a = 3
b = 4
c = a+b

加入 black box 后(只要看到了 def 开头,直到缩进不满足的 code block 都属于函数的 code):

def is_even(i):
print("inside is_even")
return i%2 == 0
a = is_even(3)
b = is_even(10)
c = is_even(123456)
其对应的为:

is_even 这个 函数名字 在 program scope 中绑定到 function object(就是本体的那段代码)。因此当有 is_even(arg) 被函数调用的时候,三次调用分别返回 False、True、True,于是全局名字 a、b、c 绑定到这些返回值。

- 每次调用都会创建自己的 local scope,formal parameter
i只在 ONLY 该次调用的局部作用域中有效(即形参脱离了函数调用时创建的作用域之后,到以外的区域就失效了); - 调用结束后,该 call frame 及其局部绑定通常结束生命周期。
7.6.2 Inserting functions in code
Remember how expressions are replaced with the value? The function call is replaced with the return value!
def is_even(i):
return i%2 == 0
print("Numbers between 1 and 10: even or odd")
# 这里实际上得 range(1,11),因为 range() 是左闭右开的
for i in range(1,11):
if is_even(i):
print(i, "even")
else:
print(i, "odd")
if is_even(i): 中的 functionion call expression 会先被 True 或 False 替代,再决定执行哪个 branch。
这样我们实现了循环和分支中调用了函数(本质上就是调用了表达式)。
7.7 Another example:sum_odd(a, b)
目标是:add all the odd integers between (and including) a and b。
- What is the input? Values for
aandb. - What is the output? The
sum_of_odds.
My work:
# 由于最后还要进行加和,且如果 a、b 有一方或者均为 odd,则要计入总和
# a、b 的相对大小需要判断一下吗?
# 我的思路是直接把 a 和 b 范围内的所有数字(包含 a 和 b)先遍历,一旦遍历的值满足奇数的定义,则记入计数器 sum_of_odds
def sum_odd(a, b):
sum_of_odds = 0
for i in range(a,b+1):
while not i%2 == 0:
sum_of_odds += i
return sum_of_odds
print(sum_of_odds)
为什么上面这个代码无限循环了?因为一旦 i 确实循环到了奇数,那么进入 while 分支的时候,只会无限地增加 sum_of_odds += i,因为在当时那一轮次中没有条件可继续更新使的 while 从循环中跳出去的。
因此,既可以跳出 for 循环,改成 while 循环,也可以改为 for 结合 if 分支:
def sum_odd(a, b):
sum_of_odds = 0
for i in range(a,b+1):
if not i%2 == 0:
sum_of_odds += i
return sum_of_odds
print(sum_of_odds)
此外,如果一开始没有声明 sum_of_odds,且全局变量中也没有,则会报错UnboundLocalError: cannot access local variable 'sum_of_odds' where it is not associated with a value,因为内存中压根找不到。
不过我认为,这里还隐藏了一个条件:默认用户输入的时候是 a < b,除非我们在 docstring 中进行了强调,否则我认为这块的逻辑仍要修改的。
Solution: Don’t write code right away!
先解决相似而更简单的问题:暂时不判断 odd,先把 a 到 b(including endpoints)的所有整数相加。
“依次查看 a 到 b 的每个数”需要 loop,可以选择 for 或 while:
def sum_odd(a, b):
for i in range(a, b):
# do something
return sum_of_odds
def sum_odd(a, b):
i = a
while i <= b:
# do something
i += 1
return sum_of_odds
- Do the summing and initialize,需要先把 accumulator 初始化为 0,然后在已经正确的循环中添加 odd 判断:
def sum_odd(a, b):
sum_of_odds = 0
for i in range(a, b+1):
if i%2 == 1:
sum_of_odds += i
print(i, sum_of_odds)
return sum_of_odds
print(sum_odd(2,4))
def sum_odd(a, b):
sum_of_odds = 0
i = a
while i <= b:
if i%2 == 1:
sum_of_odds += i
print(i, sum_of_odds)
i += 1
return sum_of_odds
print(sum_odd(2,4))
Big Idea
Solve a simpler problem first. Add functionality to the code later.
Python Tutor is also a great debugging tool。
Big Idea
Test code often. Use prints to debug.
7.7.6 You Try It:palindrome
Write code that satisfies the following specs
def is_palindrome(s):
""" s is a string
Returns True if s is a palindrome (回文,正反读都一样) and False otherwise
"""
For example:
- If
s = "222"returnsTrue - If
s = "2222"returnsTrue - If
s = "abc"returnsFalse
利用上一讲已经学过的 slicing(回文的话就是检验正反方向,反方向最好的方法就是用上负数的步长):
def is_palindrome(s):
""" s is a string
Returns True if s is a palindrome and False otherwise
"""
return s == s[::-1]
print(is_palindrome("222")) # True
print(is_palindrome("2222")) # True
print(is_palindrome("abc")) # False
7.8 Lecture summary
- Functions allow us to suppress detail from a user.
- Functions capture computation within a black box.
- A programmer writes functions with:
- 0 or more inputs
- Something to return
- A function only runs when it is called.
- The entire function call is replaced with the return value.
- Think expressions! And how you replace an entire expression with the value it evaluates to.
7.9 Supplement:Python 函数的专业概念
建议必看!! 本节为讲义后的专业补充,结合 Python 标准术语与 Fluent Python 中 first-class functions、callables 和 parameter handling 等相关概念。
7.9.1 Functions are objects and name binding
Python 中执行 def 会创建 function object,再把函数名绑定到该对象。
函数是 first-class objects(一等对象):可以赋给另一个名字、作为 argument 传入函数,也可以作为 return value 返回。
def square(x):
"""Return the square of x."""
return x*x
operation = square
print(operation(5)) # 25
- 能用
()调用的对象统称 callable object;
普通函数是 callable,但 callable 不只包括函数。这里只作概念预告,后续学习 classes 时会看到更多 callable。
7.9.2 Parameters、arguments 与位置匹配或关键词的调用方式
- parameter(形参):出现在 function definition 中的名字,如
def power(base, exponent)中的base、exponent。(作者设计时自己知道的抽象参数) - argument(实参):调用时提供的对象,如
power(2, 3)中的2、3。(即用户端提供的对象)
此外,还必须强调:
- positional argument:按位置匹配,例如
power(2, 3)。 - keyword argument:按 parameter name 匹配,例如
power(base=2, exponent=3)。
def power(base, exponent):
"""Return base raised to exponent."""
return base**exponent
print(power(2, 3)) # positional arguments
print(power(exponent=3, base=2)) # keyword arguments
Keyword arguments 能增加可读性,也允许改变传入顺序,但名称必须与函数签名匹配。
例如前面我们距离的时候,默认用户输入的值满足 a<b,一旦引入 keyword arguments 的机制,就无须担忧此顺序问题。
7.9.3 Docstrings and type hints
Docstring 通常用一句简洁描述开头,再说明必要的参数、返回值、异常或副作用。Type hints 可作为额外文档:
def molecular_mass(atom_masses: list[float]) -> float:
"""Return the total mass of all atoms."""
return sum(atom_masses)
Type hints 默认不会在运行时强制类型;它们主要服务于读者、编辑器和静态检查工具。
7.9.4 return、print()、None and side effects
return 把值交给 caller,并立即结束本次函数调用;print() 只把文本写到屏幕,是一种 observable side effect。
- 只打印而不返回结果的函数,不便于后续计算和测试。
def show_energy(energy):
print(energy) # side effect;没有显式 return
result = show_energy(-40.5)
print(result) # None
- 函数执行到末尾而没有显式
return时,自动返回None。 - Pure function(纯函数)主要由输入决定返回值,并避免修改外部状态
- 科学计算中 pure computation 往往更容易测试和复现
- 文件写入、随机数、屏幕输出或修改传入的 mutable object 都可能产生副作用,应该在 specification 中说明。
7.9.5 Avoid mutable default parameters
mutable default argument(可变默认参数) 是 Python 里面一个非常经典、也非常容易踩坑的地方。
请先记住这一点:默认参数属于函数对象,而不是函数调用。
下面这个做法规范且常见。
Default parameter object 在 def 执行时创建一次,而不是每次调用时重新创建。
因为上述的特点(函数的默认对象不是每次调用时会重新创建的!),把 list 等 mutable object 直接作为默认值,可能使不同调用意外共享状态:
# 使用 None 作为哨兵值
def record(value, values=None):
"""Append value to a fresh list unless values is supplied."""
if values is None:
values = []
values.append(value)
return values
使用 None 作为 sentinel(哨兵),并在函数体内创建新 list(而不是在函数外面,而 list 本身可变,若被多个函数调用共享,则可能导致函数出现非预期的结果),因此设置哨兵值是常见的安全写法。
先看一个错误例子,假设我们写:
def record(value, values=[]):
values.append(value)
return values
看起来很合理:
如果没有传 values,就创建一个空 list。 但是实际上不是这样。
第一次调用时:
record(1)
你可能认为:
创建一个新的 []
append(1)
返回:
[1]
实际上,Python 做的是:
函数定义的时候:
values ---> []
这个 list 已经创建好了。然后调用:
record(1)
于是:
values ---> 原来的那个 list
append(1)
所以返回:
[1]
第二次调用,现在:
record(2)
很多初学者以为:
重新创建 []
append(2)
返回:
[2]
但是实际上,Python 找到:
values ---> 之前那个 list
现在里面已经有:
[1]
于是:
append(2)
变成:
[1,2]
第三次同上,得到 [1,2,3]
所以:
print(record(1))
print(record(2))
print(record(3))
# 返回
[1]
[1,2]
[1,2,3]
为什么会这样? 这是因为,Python 的默认参数是在函数定义时计算一次,而不是调用时计算。
例如:
def record(value, values=[]):
Python 解释这个函数时,实际上类似:
default_list = []
def record(value, values=default_list):
所以,这个 list 只有一个。可以验证:
def test(x=[]):
print(id(x))
test()
test()
test()
三个 id (identity)一样。说明他们都是是同一个对象。
那为什么
None可以解决?
正确写法:
def record(value, values=None):
if values is None:
values = []
values.append(value)
return values
关键之处就是默认值设为 values=None。因为 None 是 immutable singleton
在 Python 中,None 是一个特殊对象,它不会发生 append()这种状态改变。所以第一次 record(1) 进入 values=None (而非原先的 [] 的 list!),随后 if values is None: 成立。于是 values=[] 现在才创建 list。
因此,这里创建时间不是在
def定义时,而是函数调用时。
总体来看就是第一次:
record(1)
values=None
↓
创建 []
↓
append(1)
↓
[1]
第二次:
record(2)
values=None
↓
重新创建 []
↓
append(2)
↓
[2]
所以:record(1) 和 record(2) 互相不会影响。
很多初学者会想到:
def record(value, values=list()):
或者:
def record(value, values=[]):
因为他们认为:
我只是想给一个默认空 list。
但是 Python 它只看到这是一个 list 对象,而这个对象刚好是 mutable。
为什么 None 被叫 sentinel(哨兵值)?
- sentinel 的意思:一个特殊标记,用来表示“没有提供有效值”。
例如:
def load_data(path=None):
这里 None 不代表数据,它表示用户没有提供 path 时,balabala… 当用户没有指定相应目标、路径的时候,也可以考虑用 None。
值得一提的是,
if values == None:的==内涵是 value equality(值是否相等)if values is None:这种写法更符合 Python 风格。is的内涵更像是 identity(是不是同一个对象)。- 而我们知道,
None是singleton,其values is None表达的是是否在整个 Python 程序中,只有一个 None 对象。所以values is None会更加准确。
下面这个情形是我们经常遇到的:如果用户主动传 list。 例如:
my_list = [10,20]
# 随后调用函数
record(30,my_list)
对于下面这个函数而言,
def record(value, values=None):
此时 value 的映射对象是 [10,20],所以: if values is None: 不会执行。然后:values.append(value) 返回得到 [10,20,30],这正是我们想要的。
- 一个容易混淆的地方:为什么 list 在函数内部创建没问题?
其实关键的问题是 **这个 list 是否被多个函数调用共享。**是否仅存在于自身的函数作用域。
例如下面这个例子就是安全的:
def f():
x=[]
x.append(1)
return x
每次 f() 都会创建新的 [] 所以安全。
而下面的这个例子是不推荐,甚至是危险的
def f(x=[]):
因为所有的调用共享同一个 []。
在机器学习中,就会出现这样的错误:
def collect(batch=[]):
batch.append(data)
本来想每个 epoch 收集一个新的 batch,但是实际上:
epoch 1:
batch=[data1]
epoch 2:
batch=[data1,data2]
epoch 3:
batch=[data1,data2,data3]
这就会导致最后模型训练可能出现非常奇怪的问题。
7.9.6 Scope、namespace、LEGB 与 call frame
Namespace 是名字到对象的映射。调用函数时,Python 创建 call frame,其中保存该次调用的 local namespace、当前执行位置等信息。 同一函数递归或多次调用时,每次都有各自的 frame。
Python 查找普通名字时可用 LEGB 作入门记忆:
Local:当前函数局部作用域。Enclosing:外层函数作用域。Global:当前 module 的全局作用域。Built-in:len、print等 python 自身的内置名字。
设计上应该考虑:
- 不必要的
global会让函数依赖或修改隐藏的外部状态,使测试、复用和并行执行更困难(因为影响全局)。 - 优先通过 parameters 接收所需对象,并通过
return交回结果。
7.9.7 Cohesion and single responsibility
一个函数最好完成一个清晰、cohesive(内聚)的任务。 把 data loading、computation、file output 和 plotting 全塞进一个函数,则会形成隐藏耦合。 小而有明确 contract 的函数更易于复用、组合、测试和替换;但也不必把每一行都机械拆成函数,边界应围绕有意义的职责。
7.10 ML 与计算化学中的函数设计
7.10.1 分离 pipeline 的职责
典型 ML/scientific workflow 可以分解为:
load_data(path):读取原始数据。preprocess(data, config):清洗、标准化或构建输入。extract_features(structures):从分子结构生成特征。train(model, train_data, config):训练并返回模型或训练记录。predict(model, inputs):返回预测。loss(predictions, targets):返回 scalar loss。evaluate(model, test_data):返回结构化 metrics。plot_results(results, output_path):只负责可视化和输出。
这样可以把 computation 与 file I/O、visualization 分离,避免一个 giant procedural block。
7.10.2 Scientific software wrappers
使用 RDKit、MDAnalysis、ASE、OpenMM 或 GROMACS-related workflow 时,可以把单个明确操作包装为有 specification 的函数,例如读取结构、选择原子、构建 simulation、提交外部计算或解析结果。参数可以是 arrays、molecular structure objects、file paths 或 configuration objects。
函数应清楚说明:
- 输入对象的单位、shape、坐标约定和必要前提。
- 是否修改传入的 mutable object。
- 是否读写文件、调用外部程序或使用随机数。
- 返回值的类型、单位与结构。
7.10.3 Return structured results
不要只 print 计算结果;返回能够继续处理的结构化对象更实用。
初学阶段可以返回 tuple 或 dict:
def summarize_energies(energies):
"""Return basic statistics without printing or writing files."""
# 下面这个例子返回了个字典
return {
"minimum": min(energies),
"maximum": max(energies),
"count": len(energies),
}
调用者可以决定将结果保存、绘图还是用于下游模型。
- 减少 hidden side effects、显式传入配置和随机种子,会提升 reproducibility;
- 清晰的 inputs/outputs 也为 unit testing、batch processing 和 parallel execution 做好准备。
Lecture 8: Functions as Objects
8.1 A function always returns something
上一讲定义的 is_even() 明确返回了一个 Boolean:
def is_even(i):
"""
Input: i, a positive int
Returns True if i is even and False otherwise
"""
return i%2 == 0
函数在 Python 中总会返回一个对象(可以是 boolean,integers,floats,strings…)。如果执行到 return expression,Python 先计算 expression,再把所得对象交回 caller,并立即结束本次 function call。
8.1.1 What if there is no return keyword?
def is_even(i):
"""
Input: i, a positive int
Does not return a useful result
"""
i%2 == 0
上面的函数虽然计算了 i%2 == 0,但并没有把结果交回 caller。Python 会在函数末尾隐式地补上 return None,所以它等价于:
def is_even(i):
"""
Input: i, a positive int
Does not return a useful result
"""
i%2 == 0
return None
- None is a value of type NoneType (not a string, not a number, etc);
None是NoneType的唯一对象,用来表示缺少值或没有有意义的结果。 - 没有
return不会产生 syntax error 或 static semantic error;函数仍然合法。 - 在交互式 shell 中,表达式结果为
None时通常不会显示任何内容,但这个返回值依然存在。
Big Idea
Every Python function returns a value. If no explicit return is executed, the return value is None.
8.1.2 You Try It:what is printed?
def add(x, y):
return x+y
def mult(x, y):
print(x*y)
add(1, 2) # return 3
print(add(2, 3)) # return 5,打印 5
mult(3, 4) # 先打印 12,再 return None
print(mult(4, 5)) # 执行函数时便打印 20,随后打印函数的对象为 None
把代码作为 file 运行时,输出顺序为:
5
12
20
None
具体执行过程:
add(1, 2)返回3,但是该返回值没有被print()、赋值或其他 expression 使用,所以屏幕没有输出。print(add(2, 3))先把 function call 替换成返回值5,再打印5。mult(3, 4)在函数内部打印12,随后隐式返回None;这个None没有被使用。print(mult(4, 5))先调用mult,因此打印20;随后mult返回None,最外层的print再打印None。
8.1.3 return vs. print
这一节的内容实际上我们在 第7.9.4小节 中简要介绍过。
return 和 print 的作用不同:
return只在 function body 中有意义;而print()在函数内外都能使用。- 一次 function call 最多执行一条
return,并且一旦执行,当前函数立即结束,位于它后面的 function body 不再执行;而一个函数可以执行许多次print(),执行完print()后仍可继续运行后续代码。 returnhas a value associated with it.return value把对象交给 function caller,使 function call expression 具有可继续计算、赋值或传递的值。- 事实上,
print()本身也是个函数。printhas a value associated with it.print(value)把语句关联的值只是输出到 console,是一种 observable side effect,且静态的;print()这个 function call 自身返回None,即printexpression itself returnsNonevalue
例如:
print(print(5))
# 返回
5 # 先执行括号内的函数,print(5)
None # 由于 print 将值打印给了 console,而自身不返回任何东西给 function caller,因此第二层嵌套返回了 None
具体对比可以参见如下图:

8.1.4 You Try It:fix is_triangular
- Fix the code that tries to write this function
三角数是一个数等于前面所有数之和的同时
Triangular number(三角数)是从 1 开始连续自然数之和,例如 1、1+2=3、1+2+3=6,即 1,3,6… 是 triangular number。
def is_triangular(n):
""" n is an int > 0
Returns True if n is triangular, i.e. equals a continued
summation of natural numbers (1+2+3+...+k), False otherwise """
total = 0
for i in range(n):
total += i
if total == n:
print(True)
print(False)
# 执行时可以发现如下情况
>>> is_triangular(3)
True
False # 得处理好函数的返回值问题
>>> is_triangular(4)
False
>>> is_triangular(1)
False # 这个例子的错误说明了前面 range(n) 的逻辑有问题
原代码的问题是命中结果时只 print(True) 而没有即时结束函数,并且循环结束后无条件地 print(False):
应让 Boolean 成为 return value:
def is_triangular(n):
""" n is an int > 0
Returns True if n is triangular, otherwise False
"""
total = 0
for i in range(1, n+1):
total += i
if total == n:
return True # 成立就跳出函数
return False
当 total == n 时立即返回 True,否则完整检查后返回 False。这里从 1 开始循环,也正确处理了 n = 1。
8.2 Functions support modularity
Function 把一段 computation 封装为具有 specification 的 reusable module。调用者只需知道参数和返回值,不需要复制实现,也不需要把所有细节放在同一个 program scope 中。
8.2.1 Bisection square root as a function
把前面学过的 bisection square root method 包装成函数:
def bisection_root(x):
epsilon = 0.01
low = 0
high = x
ans = (high+low)/2.0
while abs(ans**2-x) >= epsilon:
if ans**2 < x:
low = ans
else:
high = ans
ans = (high+low)/2.0
return ans
代码可以分为 initialization、iteration、interval update、new guess 和 return result。对于讲义中的 x >= 1,可以反复调用同一个 black box:
print(bisection_root(4))
print(bisection_root(123))
上述版本沿用讲义的初始区间
[0, x],其 precondition 应包括x >= 1。若要支持0 < x < 1,可以设置high = max(1, x);这一边界问题已在 Lecture 6 讨论。
8.2.2 You try it: a function can call another function
Write a function that satisfies the following specs.
def count_nums_with_sqrt_close_to(n, epsilon):
""" n is an int > 2
epsilon is a positive number < 1
Returns how many integers have a square root within epsilon of n
"""
- 得到一个整数的近似平方根的实现方法,可以复用前面一个小节的
bisection_root(),无需在新函数中重写 bisection algorithm; - For example: 执行
print(count_nums_with_sqrt_close_to(10, 0.1)),能够返回 99/100/101/102 整数,是因为打印的这四个整数的平方根与输入的参数10的误差在0.1以内。例如可以打印如下内容:
sqrt of 99 is 9.949699401855469
sqrt of 100 is 9.999847412109375
sqrt of 101 is 10.049758911132812
sqrt of 102 is 10.099456787109375
# 有 4 个整数的平方根在误差 0.1 范围内约为 10!
在写代码前,构建思路最快的方式就是动手画一些草图,例如这里就可以画一个一维坐标轴。
solution:
# 调用之前的模块
def bisection_root(x):
epsilon = 0.01
low = 0
high = x
ans = (high+low)/2.0
while abs(ans**2-x) >= epsilon:
if ans**2 < x:
low = ans
else:
high = ans
ans = (high+low)/2.0
return ans
# 开始定义新的模块
def count_nums_with_sqrt_close_to(n, epsilon):
""" n is an int > 2
epsilon is a positive number < 1
Returns how many integers have a square root within epsilon of n
"""
count = 0
# 前面已经假定 n 大于 2,进而无需担忧 bisection_root 没有考虑 [0,1] 的事情
for i in range((n+1)**2):
# 事实上,这里还可以写的更聪明、快速一些,一旦遍历到的值满足条件后重新不满足时,便终止循环,不用再等序列跑完
if abs(bisection_root(i)-n) < epsilon:
print(f'sqrt of {i} is {bisection_root(i)}')
count += 1
return count
print(count_nums_with_sqrt_close_to(10, 0.1))
#sqrt of 99 is 9.949699401855469
#sqrt of 100 is 9.999847412109375
#sqrt of 101 is 10.049758911132812
#sqrt of 102 is 10.099456787109375
#4
由于 epsilon < 1,任何满足条件的 nonnegative integer 都小于 (n+1)**2,因此这个上界足够。结果为 4,对应整数 99、100、101、102。
这一例子体现 decomposition:bisection_root() 负责“近似求一个数的平方根”,count_nums_with_sqrt_close_to() 负责“遍历候选整数并计数”:每个函数各自完成一个清晰任务。
8.3 Function scope and environments
Zooming out an function:
def sum_odd(a, b):
sum_of_odds = 0
for i in range(a, b+1):
if i%2 == 1:
sum_of_odds += i
return sum_of_odds
low = 2
high = 7
my_sum = sum_odd(low, high)

执行 def 后,global/program scope 中的名字 sum_odd 绑定到一个 function object;low 和 high 分别绑定到 2、7。调用 sum_odd(low, high) 会创建一个临时的 function-call environment,在其中计算出 15,返回后 my_sum 在 global scope 中绑定到 15。
8.3.1 How Python executes a function call
每次调用函数时,Python 都为该次调用创建一个 new function-call environment,也称 **frame(栈帧)**或 local scope(局部作用域)。可以把它看作一个暂时运行的 mini program,这与主程序所在的环境是完全分隔开的:
- 将 formal parameters 绑定到调用时提供的 argument objects (The mini program runs with assigning its parameters to some inputs);
- 在新 environment 中执行 function body;
- 遇到
return时计算并交回返回值;如果没有显式return,则交回None; - 普通函数调用结束后,该次调用的 temporary frame 不再作为当前执行环境,本次调用的环境消失 (The environment disappears after it returns the value),在那个函数调用环境中创建的任何变量也会消失;
- 这时候主程序接收到返回的值,随后继续完成主程序的任务,此时只留下主程序中的内容。
Global environmen (全局作用域) 是程序开始执行的地方,也是顶层名字所在的 scope。 Scope 本质上是 names 到 objects 的 mapping,并决定当前 expression 中的名字应该解析为哪个对象。
- Environments
- Global environment
- Where user interacts with Python interpreter
- Where the program starts out
- Invoking a function creates a new environment (frame/scope)
- Global environment
8.3.2 Variable scope:step through a call
当函数调用时,这些环境是如何互相影响的?事实上环境之间一般互不干扰,他们只是通过传递参数和返回值来互相干扰。因此,这两个不同的环境(主程序环境和函数调用环境)事实上可以有相同名称的变量,且互不干扰(一般而言是这样的,但前面学习 tcl 语言的时候,我们知道可以通过一些函数来影响 global 和 local,例如 tcl 语言中的可以在 proc 中使用 global <value> 来调用全局变量)。
- Formal parameters get bound to the value of input parameters
- Scope is a mapping (映射) of names to objects
- Defines context in which body is evaluated
- Values of variables given by bindings of names
- Expressions in body of function evaluated wrt this new scope
# 进行函数的定义
def f(x):
# x 是一个 formal parameter, because there is no actual value associated with them, we're writing this function assuming that at some point we're going to get a initial value for x.
# so, x is just a abstract variable
x = x+1
print("in f(x): x =", x)
return x
# 下面实际上是在主程序的作用域中进行函数调用
y = 3
z = f(y) # y is actual parameter; initializes a variable x; make a function call f(x),当函数调用时这个实参会映射到形参上面; assigns return of function to variable z; can be any legal value
逐步来看:
- 执行
def,global namef绑定到 function object。 y = 3,global namey绑定到 int object3。- 调用
f(y),创建f的 local frame,并让 local parameterx绑定到调用处求得的对象3。 - 在
f的 scope 中执行x = x+1:先求得新 int object4,再让 local namex改为绑定4;global namey仍绑定3。 - 函数打印
in f(x): x = 4,随后返回4。 - 整个
f(y)expression 被返回值4替换,global namez绑定到4。
最终有 y == 3、z == 4。
local parameter name 与 caller 使用的变量名不必相同(即便相同,也不会有命名冲突),关键是调用时计算出的 object 被绑定到对应 parameter。
一些参考的过程图如下:
从最终结果不难看出,如果此时在 interpreter 中打印 x,显然只能是返回 3,此前 function scope 消失了,与之同时创建的形参也消失了.
Big Idea
You need to know what expression you are executing to know the scope you are in. 知道自己的表达式是在哪个 scope 很重要!否则参数可能对不上!
8.3.3 Accessing and rebinding outer names
下面是一些其他的 scope example,需要注意的是这几个例子在 python 上行得通,是 python 的特点,在别的语言上可能就行不通!
- Inside a function, can access a variable defined outside
- Inside a function, cannot modify a variable defined outside (actually you can do this thing by using global variables, but frowned upon(不推荐和赞成此做法))

Case 1:
f(x) 这个函数内可以读取 outer/global scope 中能够解析到的名字,如果更大的环境没有能够解析到的值,就会继续向外查找,直到没有环境可以查看。但对某个名字进行赋值时,Python 默认把它视为是当前函数的 local name,进而不影响外部。
f 内部创建并修改的是 local x,不影响 global x,所以他们是不同的对象。
def f(y):
x = 1
x += 1
print(x)
x = 5
f(x)
print(x)
# 输出:
2 # 这个是函数的 code 打印出来的
5 # 这个是实际当中的 global scope 中 x 绑定的值
Case 2:
g 没有给 x 赋值,所以读取时会在 outer scope 找到 global x;parameter y 在这个函数体中其实没有被使用。
def g(y):
print(x)
print(x+1)
x = 5
g(x) # x inside g is picked up from scope that called function g
print(x)
# 输出得到
5 # 这两个值明显是函数调用打印出来的;执行 g(x) 时,实际就是执行的 g(5),但一进入 f scope 的时候在函数内部并没有 print(x) 中所定义的 x 赋值,正常一般是 print(y),因此这里函数会尝试在 outer scope 中 access global x,从而打印出5
6 # 这两个值明显是函数调用打印出来的;
5 # 此时打印的是主程序中的 print
执行 g(x) 时,实际就是执行的 g(5),但一进入 f scope 的时候在函数内部并没有 print(x) 中所定义的 x 赋值,正常一般是 print(y),因此这里函数会尝试在 outer scope 中 access global x,从而打印出 5。本质上,这个写法只是函数访问了一个变量,并将其打印了出来。
不难发现,此时在 function 内部本身并没有赋值 x,因此若擅自以为能访问 x 就可以修改 x 的话,例如 x += 1,这时候就报错。因为本身 x 就是访问 outer scope 借来的,如果修改就没有这种权限,本身在 f scope (抽象地来说就是 local scope) 中就没有赋值。
要解决这种问题就得在函数内部隐式依赖于 global <variables>,这样才能获得“修改权限,但这种做法不是我们推崇的先创建赋值的显式声明。下面这个 case 3 就展示了如果这么操作就会报错。
Case 3:
def h(y):
x += 1
x = 5
h(x)
print(x)
这段代码触发 UnboundLocalError。虽然 h(x) 成功地解析 x 为 outer scope 中的 x = 5 并进行了映射为了 h(5)。但 x += 1 同时包含读取和赋值,而赋值使 Python 把 x 判定为 local name;当读取 expression 并计算右侧时,这个 local x 尚未绑定任何对象,因此直接报错 UnboundLocalError。
- 虽然可以使用
global x强制修改 global binding,但这种隐式依赖通常会降低函数的可测试性。 - 更清晰的写法是使用 parameter 和 return value 来进行传参。下面这种写法就很好,实现了外部变量的更新:
def h(y):
return y+1
x = 5
x = h(x)
print(x) # 6
8.4 Functions as first-class objects
- fuctions as arguments i.e., functions as first-class objects (将函数用作其他函数的参数)
8.4.1 Higher-order procedures
Python 中的对象具有 type,例如 int、float、str、bool、NoneType 和 function。事实上,前面我们定义的这些 function 通过 type(is_even) 查询返回的是 function 这样的对象类型。因此,function 从根本上来说就是一个 object(对象)。
进而,对象可以出现在 assignment statement 的右侧(因此可以有两个以上的名字同时指向同一个函数代码的函数),可以作为 argument 传入 procedure,也可以作为 procedure 的 return value。
Functions are first-class objects(一等对象),因此函数和其他 object 一样可以:
- 在运行时由
def或lambda创建。 - 绑定到名字,也可以存入 data structure。
- 作为 argument 传给另一个函数。
- 作为另一个函数的 return value。
接收 function argument 或返回 function object 的函数称为 higher-order function/procedure(高阶函数/过程)。
8.4.2 Objects in a program
def is_even(i): # 这一行创建了 is_even 的名字与函数对象 ( 那些 code body) 绑定在内存中,就像一个绑定了值的变量名一样
return i%2 == 0
r = 2
pi = 22/7
my_func = is_even # 注意,is_even 本身就是个有名字的对象,就跟 r=2,y=2 ,z=y 一样,对象可以同时被多个名字绑定或传递
a = is_even(3)
b = my_func(4)
注意下面的云图:

这里的 binding 关系为:
r绑定到 int object2。pi绑定到计算所得的 float object。is_even与my_func是两个名字,但绑定到同一个 function object;my_func = is_even没有调用函数,因为没有(),只是个名字!。a绑定到False,b绑定到True;my_func(4)证明 alias 同样可以调用该 function object。
print(type(is_even)) # <class 'function'>
print(my_func is is_even) # True
Big Idea
Everything in Python is an object. Function names are names bound to callable function objects.
8.5 Functions as arguments
8.5.1 Function as a parameter
观察下面这个例子:
def calc(op, x, y):
return op(x, y)
def add(a, b):
return a+b
def div(a, b):
if b != 0:
return a/b
print("Denominator was 0.")
# 这是一个测试
print(calc(add, 2, 3)) # 5
# 事实上就是嵌套多个 scope,一开始在 calc(add, 2, 3) 中,add 作为函数对象 function object,而非 add() 这样的函数调用 function call。
# 因此,先是进入 calc 绑定的函数对象,进行参数的映射,继而接收到了 add(2,3) ,进而继续执行进一层的 scope
调用 calc(add, 2, 3) 时,第一个 argument 是 function object add,而不是 add() 的调用结果。calc 的 local parameter op 绑定到该 function object,因此 op(x, y) 等价于本次调用中的 add(2, 3)。
这让 calc 不需要写死具体 operation。只要传入的 callable 能接受两个 arguments,calc 就可以应用它。
8.5.2 Nested function calls create separate frames
对 res = calc(add, 2, 3) 逐步追踪:
- Global scope 中的
calc、add、div分别绑定到各自的 function object,并放置于内存当中; - 调用
calc,创建 calc frame:op -> add、x -> 2、y -> 3。
- 在 calc frame 中执行
op(x, y),也就是调用add(2, 3);这又创建独立的 add frame:a -> 2、b -> 3。
add计算a+b并返回5,add frame 完成本次工作。- calc frame 中的
op(x, y)被5替换,calc再把5返回 global caller。
- Global name
res绑定到5。
因此嵌套调用会暂时形成 call stack:global code 等待 calc,calc 等待 add;最内层先返回,然后逐层回到 caller。
8.5.3 You Try It:calc(div, 2, 0)
res = calc(div, 2, 0)
div(2, 0) 进入 b == 0 的情况,打印:
Denominator was 0.
随后 div 隐式返回 None,calc 也把这个 None 返回,因此 res is None。若再执行 print(res),才会额外打印 None。
8.5.4 Another example:functions as parameters
def func_a():
print("inside func_a")
# note: func_a() no bindings (no parameters), and return None, so print None
def func_b(y):
print("inside func_b")
return y
def func_c(f, z):
print("inside func_c")
return f(z)
print(func_a())
print(5+func_b(2))
print(func_c(func_b, 3))
完整输出为:
inside func_a
None
inside func_b
7
inside func_c
inside func_b
3
func_a()先产生 print side effect,再隐式返回None,所以 outerprint显示None。func_b(2)先打印一行,再返回2;表达式变为print(5+2),所以显示7。func_c(func_b, 3)的 parameterf绑定到func_b。它先打印inside func_c,再调用func_b(3);后者打印inside func_b并返回3,最终 outerprint显示3。

8.5.5 You Try It:apply(criteria, n)
Write a function that meets these specs.
def apply(criteria, n):
"""
criteria is a func that takes in a number and returns a bool
n is an int
Returns how many ints from 0 to n (inclusive) match the criteria
"""
实际上就是写一个模板,此后当你用别的函数(某种人为制定的判定函数,此后抽象为 criteria)作为函数对象进入 apply 这个函数的时候,能够判断出满足条件为 True 的个数有多少个。
Solution:
def apply(criteria, n):
""" criteria is a function taking a number and returning a bool
n is a nonnegative int
Returns how many ints from 0 to n inclusive satisfy criteria
"""
count = 0
for i in range(n+1):
if criteria(i):
count += 1
return count
def is_even(i):
return i%2 == 0
# return a boolean value
print(apply(is_even, 5)) # 3,对应 0、2、4
how_many = apply(is_even, 5)
这里 criteria 是对行为的抽象:apply 不需要知道“偶数”“正数”或其他规则的实现,只依赖 specification——传入对象可用一个 number 调用,并返回可用于判断的 Boolean。
由上面这几个例子我们可以得知:operatin 和某一个判定的 criteria 是可以被抽象出来的,这个思想在日后我们构建 higher-order function 以及利用模块化思想和抽象与解构的时候非常有用。
Big Idea
Passing behavior as a function argument lets one general algorithm work with many criteria or operations.
8.6 Summary
- Python function 总会返回一个对象;没有显式
return时返回None。 return把值交给 caller 并结束调用;print()产生 console output,自身返回None。- HAVE TO BE CAREFUL ABOUT ENVIRONMENTS:
- Main program 在 global environment 中运行
- 每次 function call 都建立新的 temporary environment/frame。
- Scope 是 names 到 objects 的 mapping;local rebinding 与 global binding 应区分清楚。
- Functions are first-class objects:有 type、可绑定到其他名字、可作为 argument,也可作为 return value。
- Higher-order function 接收或返回 function object,使代码能够抽象 operation 或 criteria。
- Nested function calls 各有独立 frame,并按 call stack 从内层向外返回。
8.7 Supplement:first-class functions 的专业概念与常见写法
本节为 Lecture 8 主体后的补充,主要参考 Fluent Python: Clear, Concise, and Effective Programming, 2nd Edition Chapter 7 “Functions as First-Class Objects”,并补充相关 CS 术语和 Python 惯用写法。
8.7.1 Function object 的属性与 introspection
这一节在实际中很有用,我们可以利用解释器来检查函数完成 introspection(内省)。
记住这几个!(其中是两个下横线)
print(type(factorial))print(factorial.__name__)print(factorial.__doc__)
执行 def 会在 runtime 创建 function object。
函数具有普通对象的 type、identity 和 attributes:
def factorial(n):
"""Return n factorial for a nonnegative integer n."""
result = 1
for i in range(2, n+1):
result *= i
return result
print(type(factorial)) # 返回 <class 'function'>
print(factorial.__name__) # 返回函数名 factorial
print(factorial.__doc__) # 返回函数内封装的 docstring 的文本
help(factorial) # 利用 metadata 生成帮助信息
# 例如 help(factorial) 返回如下信息
Help on function factorial in module __main__:
factorial(n)
Return n factorial for a nonnegative integer n.
__name__、__doc__等 metadata 允许解释器、IDE、documentation tool 和 framework 检查函数。这里的 introspection(内省) 指程序在 runtime 检查对象自身的类型、属性或接口信息。
8.7.2 Callable 不只包括普通函数
这一小节我们来介绍 cllable()
- 能应用 call operator
()的对象统称 callable object(可调用对象)。 - 判断对象能否调用时,使用内置函数
callable()比只检查type(obj) is function更稳妥:
objects = (abs, str, "not callable")
print([callable(obj) for obj in objects])
# [True, True, False]
下面我们讲解一下上面这段代码是何意味。
这里需要介绍的是,objects 是一个 tuple,其中里面封装了三种对象:
abs# 绝对值函数,是内置函数对象str# 字符串,是一种类对象,class"not callable"# 字符串实例
所以上面的代码等价于:
result = []
for obj in objects:
result.append(callable(obj))
print(result)
# 继而 callable 循环判断 objects 数组中的几个值,并返回判断的 boolean 结果
需要注意的是,这里判断的是函数对象本身,例如 abs,而例如 abs(-5) 则是调用函数。
str 虽然是 class,而不是普通函数,但 Python 中 class 也是 callable object。
调用一个 class 通常会创建并初始化一个 instance,例如:
text = str(123)
print(text) # 123
print(type(text)) # <class 'str'>
因此,概念上调用 str(123) 会经过该 class 的对象创建和初始化过程,最后返回一个字符串实例,所以 callable(str) 是 True。类似的还有:
callable(int) # True
callable(list) # True
callable(dict) # True
因为对于 int/list/dict 这些都是 class object,也都可以被调用。
最后我们回到 "not callable",本质上这是一个由 str class 创建出来的一个 instance 实例。而普通字符串实例没有定义“被调用”这种行为,因此不能写为 "not callable"(),进而报错 TypeError: 'str' object is not callable。
therefore:
str # class object,可以调用
"not callable" # str instance,不可以调用
但事实上,class 创建出来的 instance 是否可以调用,要看其 class 是否提供 __call__ 行为。
在 Python object model 中,一个对象是否可调用,主要取决于它的 type 是否提供调用行为,通常表现为特殊方法:__call__。
例如,自定义 class 可以通过实现 __call__(),让它的 instance 也变得 callable:
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return self.factor*value
创建 instance:triple = Multiplier(3)。虽然 triple 不是普通函数,但它可以调用:
print(triple(7)) # 21
这基本等价于:
print(triple.__call__(7)) # 21
因此:
print(callable(triple)) # True
调用 triple(7) 时,Python 根据 triple 的 type 找到相应的调用机制,最终执行 Multiplier.__call__(triple, 7)。
- 在 CPython 的底层,
callable()大致通过 PyCallable_Check 检查对象的 type 是否设置了相应的调用槽位 tp_call。
因此,更准确的说法不是简单检查:hasattr(obj, "__call__"),而是检查这个对象的类型系统是否支持调用操作。
therefore:
callable(obj) == True –> 不等于任意调用都成功
callable() 只表示对象具有调用能力,不表示你提供的 arguments 一定正确。
例如,callable(abs) # True。但abs() 依然会报错,因为 abs 需要一个 argument,故报错信息为 TypeError: abs() takes exactly one argument。
常见 callables 包括:
- user-defined function
- built-in function
- method
- class
后续学习 class 时还会看到,只要 instance 的 class 定义了 __call__,该 instance 也能像函数一样调用;generator function、coroutine function 等也属于 callable,但调用后返回的是需要进一步迭代或等待的对象。
8.7.3 Higher-order function、callback 与 strategy
Higher-order function 的正式定义是:接收 function/callable 作为 argument,或返回 callable 作为结果。
Python 标准接口中最常见的例子之一是 sorted(iterable, key=...):
words = ["strawberry", "fig", "apple", "banana"]
print(sorted(words, key=len))
# ['fig', 'apple', 'banana', 'strawberry']
key接收一个 one-argument callable;- 排序算法会对每个 element 调用它,并按所得 key 排序
- 原 elements 不会因为计算 key 而被改写。
当函数作为参数交给另一个组件,并由该组件在合适时机调用时,常称为 callback(回调)。当多个函数表示可以互换的算法或规则时,也可把它们理解为不同 strategy(策略):
def add(a, b):
return a+b
def multiply(a, b):
return a*b
operations = {
"+": add,
"*": multiply,
}
symbol = "*"
result = operations[symbol](6, 7)
# symbol 是 *,也是 dictionary 的 key,然后进入库中对应的 value 为 multiply,而 multiply 这个函数则对应 6*7
print(result) # 42
像上面这种做法实际上就是 dispatch table。
operations 是 dispatch table(分派表):把输入标记映射到 function object。与一长串 if/elif 相比,新增 operation 时通常只需定义函数并增加一条 mapping。
8.7.4 Returning a function and function composition
First-class function 也能作为 return value。最简单的写法是根据条件返回已经存在的 function object:
def choose_operation(symbol):
if symbol == "+":
return add
if symbol == "*":
return multiply
raise ValueError("unsupported operation")
op = choose_operation("+")
print(op(2, 3)) # 5
还可以构造并返回新函数,实现 function composition(函数组合):
def compose(f, g):
"""Return a function that computes f(g(x))."""
def composed(x):
return f(g(x))
return composed
def double(x):
return 2*x
def square(x):
return x*x
square_after_double = compose(square, double)
print(square_after_double(3)) # 36
返回的 composed 仍能使用创建它时的 f 和 g;这种保留 lexical environment 中绑定的函数对象称为 closure(闭包)。这里只需先理解它是“function object 连同其需要的外部绑定”,decorator 章节会进一步展开。
8.7.5 map、filter、comprehension 与 reducing functions
map(function, iterable) 与 filter(criteria, iterable) 都是 higher-order functions。
Python 3 中它们返回 lazy iterator,需要迭代或用 list() materialize:
def square(x):
return x*x
print(list(map(square, range(6))))
# [0, 1, 4, 9, 16, 25]
对于简单转换和筛选,list comprehension 或 generator expression 通常更直观,并可同时表达 mapping 与 filtering:
squares_of_odd = [n*n for n in range(6) if n%2 == 1]
print(squares_of_odd) # [1, 9, 25]
把 sequence 聚合为一个结果称为 reduction(归约)。求和优先使用 sum(),逻辑检查常使用 all() 与 any();这些具体 built-ins 往往比通用 functools.reduce() 更容易读:
values = [2, 4, 6]
print(sum(values)) # 12
print(all(v%2 == 0 for v in values)) # True
print(any(v < 0 for v in values)) # False
8.7.6 lambda:适合短小的一次性 expression
lambda expression 创建 anonymous function object,适合在 higher-order function 的 argument 位置写一个简短规则:
words = ["strawberry", "fig", "apple", "banana"]
print(sorted(words, key=lambda word: word[::-1]))
lambda 的 body 只能是一个 expression,不能直接包含 while、try、普通 assignment 等 statements。若逻辑需要解释、复用、测试或多步处理,使用有意义名字的 def 通常更清楚:
def reversed_spelling(word):
return word[::-1]
print(sorted(words, key=reversed_spelling))
判断标准不是字符数,而是可读性:当必须写一段注释才能解释 lambda 时,注释本身往往已经提示了一个合适的 function name。
8.7.7 operator module:把运算与取值写成 callable
标准库 operator 提供许多 operator 的 function form,例如 add、mul、itemgetter、attrgetter 和 methodcaller,可以减少只为转交一个简单操作而写的 lambda。
from operator import itemgetter
measurements = [
("sample_B", 0.12),
("sample_A", 0.08),
("sample_C", 0.15),
]
print(sorted(measurements, key=itemgetter(1)))
# [('sample_A', 0.08), ('sample_B', 0.12), ('sample_C', 0.15)]
itemgetter(1) 是一个 function factory,返回的 callable 对输入执行 [1]。类似地,attrgetter("energy") 可从 objects 中读取指定 attribute,methodcaller("strip") 可创建调用指定 method 的函数。
8.7.8 functools.partial:预先固定部分 arguments
functools.partial 接收一个 callable,并预先绑定其中一部分 positional 或 keyword arguments,返回一个新的 callable。这称为 partial application(部分应用):
from functools import partial
from operator import mul
triple = partial(mul, 3)
print(triple(7)) # 21
mul 需要两个 arguments,而 triple 已经固定第一个 argument 为 3,所以调用者只需再给一个。它常用于把已有函数适配到只接受特定 callback signature 的 API:
def scale(value, factor):
return value*factor
to_percent = partial(scale, factor=100)
print(to_percent(0.375)) # 37.5
8.7.9 Argument passing:call by sharing
Python 的 parameter passing 常用 **call by sharing(共享传参)**来描述:function parameter 得到的是 argument 所引用对象的另一个 reference。函数内对 parameter name 重新绑定,不会改变 caller 中名字的 binding:
def increment(value):
value = value+1
return value
x = 10
y = increment(x)
print(x, y) # 10 11
这里没有把 caller 的 x 改成 11;local value 只是重新绑定到新 int object。后续学习 mutable collections 时还要区分另一种情况:函数虽然不能通过 local rebinding 改变 caller 的名字,却可能通过 method 修改双方共同引用的 mutable object。函数 specification 因此应说明是否产生这种 side effect。
8.7.10 Common design rules
- 若函数只负责计算,优先
returnstructured value,把print、file I/O 等 side effects 留给 caller 决定。 - 接收 callable 的函数应在 docstring 中说明其 expected signature,例如 “takes one number and returns a bool”。
- 把 function object 传参时写
apply(is_even, 5);若写成apply(is_even(), 5)会先调用is_even,传入的是其 return value,而且还可能因缺少 argument 直接报错。 - 避免依赖或修改不必要的 global state;通过 parameters 显式输入,通过 return values 显式输出。
- Higher-order functions 能把“遍历或控制流程”与“具体 operation/criteria”分开,常用于 sorting key、callback、validation rule、event handler、numerical pipeline 和 data transformation。
Lecture 9: Lambda Functions, Tuples, and Lists
这一节我们将介绍一类名为 lambda 的函数,从而创建一种 anonymous functions。就此我们结束如何创建函数的探索,进而介绍 tuples(数组)和 list(列表)。
9.1 Anonymous functions:lambda
Lecture 8 中的 apply() 接收一个 criteria function,并统计从 0 到 n(inclusive)之间有多少个 integers 满足该判定条件:
def apply(criteria, n):
""" criteria is a function that takes in a number and returns a bool
n is a nonnegative int
Returns how many ints from 0 to n inclusive satisfy criteria
"""
count = 0
for i in range(n+1):
if criteria(i): # 假定这里 func 返回的 boolean value 为 True
count += 1
return count
def is_even(x):
return x%2 == 0
print(apply(is_even, 10)) # 6,对应 0、2、4、6、8、10
如果 don’t want to name functions especially simple ones(任务简单懒得留名),并且只准备在 argument position 使用一次,则可以用 lambda expression 当场创建 anonymous function(匿名函数):
# 原先简单的函数:
def is_even(x):
return x%2 == 0
# 创建等价的匿名函数!
# can use an anonymous procedure by using lambda
lambda x: x%2 == 0
p.s. lambda 对应我们常见的希腊字母 $\lambda$ 字符
语法可以概括为:
lambda parameter_1, parameter_2, ...: expression

lambda后面是 parameters,冒号后面是 function body;body 只能写一个 expression。- 调用时 Python 计算这个 expression,并把结果作为 return value,所以不用写
returnkeyword。 lambda会创建 procedure/function object,但这个 expression 本身不会像def is_even(...):一样自动把它绑定到一个 name。即 does not bind a name to it- 这也意味着
lambdafunction is one-time use. It can’t be reused because it has no name!
因此,前面的 named function 可以直接以内联形式传给 apply():
def apply(criteria, n):
""" criteria is a function that takes in a number and returns a bool
n is a nonnegative int
Returns how many ints from 0 to n inclusive satisfy criteria
"""
count = 0
for i in range(n+1):
if criteria(i): # 假定这里 func 返回的 boolean value 为 True
count += 1
return count
# Function call with a named function:
apply(is_even, 10)
# Function call with an anonymous function as parameter:
apply(lambda x: x%2==0, 10)
print(apply(lambda x: x%2 == 0, 10)) # 6
这里传入的仍然是 function object。apply 的 local parameter criteria 绑定到该 anonymous function,并在每轮循环中通过 criteria(i) 调用它。
lambda虽然在讲义中声称是 one-time use,是因为这里没有保存它的 reference,调用结束后无法在后续代码中按名字复用。 然而,在技术上可以写is_even = lambda x: x%2 == 0,但需要命名和复用时,def is_even(x): ...通常更清楚。
9.1.1 You Try It:trace do_twice
- What does this print?
def do_twice(n, fn):
# 事实上就嵌套 fn() 重算两次
return fn(fn(n))
print(do_twice(3, lambda x: x**2))
do_twice 的 function-call environment 中有 n -> 3、fn -> lambda x: x**2。Python 先计算 inner call fn(n):
fn(3) -> 3**2 -> 9
随后 outer call 使用第一次的 return value:
fn(9) -> 9**2 -> 81
因此最终打印 81。两个 fn(...) 是两次不同的 function call,每次都会建立自己的 lambda frame;expression evaluation 的顺序是由内向外,而不是把 3 只平方一次。
大致流程示意图如下:

Big Idea
lambda creates an anonymous function object. It is useful when a simple behavior is needed once and can be expressed clearly in one expression.
9.2 A new compound data type:sequence
在之前,我们介绍的内容仅仅是如何将已经使用过的代码封装到一个函数中,并没什有太多新的语法,而这一节我们将开始介绍新的封装相关的语法。而这涉及到两种 data types —— tuple (数组/元组) and list(列表)
几个 termiologies:
- scalar type (e.g.,
int/float/bool) - None type:
None - compound type (符合数据类型,e.g.,
str),因为其可以本质是一堆字符组成,我们可以通过索引字符串来 grab 字符 - more general compound data types (e.g.,
tuple,list,dictionary)
此前接触过 int、float、bool 等 scalar types,也接触过 compound type str。
这一讲进一步引入 more general compound data types:
务必牢记一下几点:
- Tuple 是 immutable sequence
- List 是 mutable sequence
- indexed ordered sequences of objects/elements(由对象组成、可以用 index 访问的有序序列), which could themselves be compound structures. 一个 sequence 的 element 本身也可以是 compound object,因此可以构造 tuple of tuples、list of lists,或在 tuple 中放 list。
- 有 index 意味着我们在可以像在 slice 中可以根据 index 来 slicing;在之前的 tcl 语言中可以用
lindex/lsearch/lrange/lappend/lreplace/linsert/llength等等这些就可以利用 index 来对 list 进行一系列操作。
Tuple、list 和 string 都支持 indexing、slicing、len() 以及按顺序迭代,因此我们可以将其与 string 进行类比;
而他们的核心差异在于所保存的 element references 能否被替换,以及 collection 的长度能否原地改变。
下一节我们也将介绍 mutability、aliasing、cloning 等概念。
9.3 Tuples
- Tuple(元组/数组)是 indexable ordered sequence of objects(可索引的有序对象序列)
- 可以保存不同 type 的 objects,例如 int, string, tuple, tuple of tuples, …
- Tuple 本身 immutable:创建后不能替换、删除或增加它的 element values
9.3.1 Tuple literals and basic operations
有些 tuple 和 list 相关的操作将与我们前面在 string 上学的 subscription 执行的完全相同。无非就是 indexing/slicing/getting the length.
p.s. tuple 有两种读法,其中一种是基于 n-tuples 而来的,n元组
te = () # empty tuple,类似于空的字符串 ""
ts = (2,) # tuple with one element. extra comma means with one element, compare with ts = (2)
t = (2, "mit", 3) # multiple elements in tuple separated by commas
t[0] # evaluates to 2, because indexing starts at 0;这实际上是一种先前介绍过的 subscription
(2,"mit",3) + (5,6) # evaluates to a new tuple (2, 'mit', 3, 5, 6),这里会自动加空格,因此规范来说前面我们写 expression 的时候最好也是加入空格
t[1:2] # ('mit',);因为是 0-based,从 1 号元素 "mit" 开始,到 2 号元素 3 结束但不包含第 2 号元素,最后还会给出逗号对 single-element tuple 和 integer expression 进行区分
t[1:3] # ('mit', 3)
len(t) # 3
# 事实上可以用 max, min, sum 等函数来获取最大元素、最小元素或对我的 tuple
t[1] # gives error, can’t modify object
这里有几点需要强调的事情 (再次强调 immutable!):
- 构造 single-element tuple (只有一个元素的 tuple) 时必须保留 comma。更一般地说,tuple literal 的关键是 commas,parentheses 主要用于让结构更清楚或避免语法歧义。
例如,
(2)只是带括号的 integer expression,结果仍为2;(2,)才是 tuple。逗号就是为了区分只有有一个元素的数组,例如下面这个运行结果:
# 比较这两个运行的结果的区别!
>>> a = (5)
>>> type(a)
<class 'int'>
>>> a
5
>>> b = (4,)
>>> type(b)
<class 'tuple'>
>>> b
(4,)
- Tuple 支持 concatenation,但
+计算得到的是一个 new tuple,不是修改原对象:
t = (2, "mit", 3)
new_t = t+(5, 6)
print(new_t) # (2, 'mit', 3, 5, 6)
print(t) # (2, 'mit', 3)
- 以下代码会报错,因为 tuple 不支持 item assignment:
t[1] = 4
# TypeError: 'tuple' object does not support item assignment
这实际上类似于前面我们学的字符串 immutable 一样,无法进入内存,进而修改不了内存中的值:
>>> s = "yuanshen niubi"
>>> s[1]
'u'
>>> s[1]=2
Traceback (most recent call last):
File "<python-input-12>", line 1, in <module>
s[1]=2
~^^^
TypeError: 'str' object does not support item assignment
这一点与 list 有很大的不同,下一节我们将学习 list 的相关内容。
对于 tuples 或 strings,一旦在内存中创建了字符串 ABCN,就不能进入内存并更改这个字符串。不过你可以基于这个字符串创建新对象的绑定(例如
t这个变量改变绑定,但原先的对象仍旧躺在内存中),但不能进入并修改这个对象。这一点实际上和前面我们讲过的变量是一致的道理。
- 下面这个例子则告诉我们当用
max、min、sum等函数的时候仍旧要遵守基本的求值规范。
>>> max((3,5,0)) # 5 的数值最大
5
>>> max(("yuan","shen","nb")) # yuan 的字符串长度最长
'yuan'
>>> max(("yuan",9,"nb")) # 没法比较 int 和 str,一个是 scalar (标度) type,一个是 compound type
Traceback (most recent call last):
File "<python-input-9>", line 1, in <module>
max(("yuan",9,"nb"))
~~~^^^^^^^^^^^^^^^^^
TypeError: '>' not supported between instances of 'int' and 'str'
9.3.2 Indices, slicing, and iteration
seq = (2, 'a', 4, (1, 2))
# index: 0 1 2 3
# index: -4 -3 -2 -1
print(len(seq)) # 4
print(seq[3]) # (1, 2)
print(seq[-1]) # (1, 2)
print(seq[-2:]) # (4, (1, 2))
print(seq[1:4:2]) # ('a', (1, 2))
print(seq[:-1]) # (2, 'a', 4); 只要不指认方向,那么默认从正向的 index 开始出发,而前面省略了从0开始,到-1的index,即本质是 3 的 index(因为步长仍为正向)
print(seq[1:3]) # ('a', 4)
# 下面这几个例子务必好好体会:
print(seq[3][0]) # 1;拆成两部分看,先看 seq[3] ,再看 seq[3] 对应的 0 index,即 (1,2) 的 0 index 为 1,故返回 1
# 这个例子很好地体现了 tuple 在 index 这一块也和 string 有着很高的相似之处
>>> s = "woso"
>>> s[4]
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
s[4]
~^^^
IndexError: string index out of range
>>> seq = (2, 'a', 4, (1, 2))
>>> seq[4]
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
seq[4]
~~~^^^
IndexError: tuple index out of range
- 着重分析
seq[3][0]seq[3]先取得 nested tuple(1, 2),seq[3][0]再在该 tuple 中取 index0。
- Negative index 从末尾计数,所以
seq[-1]是最后一个 element。 - Slice
seq[start:stop:step]的stop不包含在结果中;slicing 的结果仍是 tuple,并且不会修改原 tuple。对于非完整 slice,结果通常是包含所选 references 的新对象;某些 implementation 可以直接复用完整的 immutable tuple,例如 CPython 中的seq[:]。 - 这一点得好好体会区别:
seq[4]会触发IndexError,因为长度为4的 sequence 只有0到3四个有效 indices;而合法 slice 即便越过边界通常也会被截断,而不会因此报错。
Tuple 是 iterable,可以直接依次取得 elements(iterating over sequences,遍历序列!):
for e in seq:
print(e)
# 2
# a
# 4
# (1, 2)
9.3.3 Swapping values and tuple unpacking
tuple 有一个用处就是可以快速地交换赋值。
之前我们提到过,直接顺序赋值不能正确交换两个 variables:
x = 1
y = 2
x = y
y = x
print(x, y) # 2 2,原来的 1 已经失去 binding
此前我们讨论过,可以引入 temporary variable 的做法:
x = 1
y = 2
temp = x
x = y
y = temp
但在这一节,我们也可以使用更为方便的 tuple packing/unpacking:
x = 1
y = 2
(x, y) = (y, x) # 先得到右边为 (2,1) ,再分别匹配赋值过去得相应的元素
# 也可以简略写成:
x, y = y, x
print(x, y) # 2 1
执行 x, y = y, x 时,Python 先计算右侧并把两个 references 组织为一个 tuple-like value,再把它们分别绑定给左侧 names。因此不会发生第一个 assignment 覆盖第二个 assignment 所需旧值的问题。
这里两侧的 parentheses 都可以省略,写成
(x, y) = (y, x)只是把 packing/unpacking 的结构显示得更明显。

9.3.4 Returning more than one value
前面我们在介绍函数的时候,基本没能见到函数返回多个值;事实上,因为 tuple 是个对象,因此,tuple 还有一种用法那就是从函数那边返回更多的值(因为可以封装更多的 value)。这也意味着在后续的机器学习中我们对其注入向量的时候也可以如是操作。
def quotient_and_remainder(x, y):
q = x//y
r = x%y
return (q, r)
# one object! (with 2 elements/values)
# for example:
both = quotient_and_remainder(10, 3)
print(both) # (3, 1)
# 这里运用到了前面的 packing/unpacking 技巧
(quot, rem) = quotient_and_remainder(5, 2)
# 或写成:
quot, rem = quotient_and_remainder(5, 2)
print(quot) # 2
print(rem) # 1
# 体会这两种区别
>>> print(quot, rem) # 因为这里前面 unpacking 的时候已经绑定了这两个 elements,因此也是两个在内存中有绑定值的对象,故这里实际上就是 quot + 逗号(string打印出来就是空格)+ rem 的结果了
2 1
>>> print((quot, rem)) # 多一个括号才意味着在打印 tuple,因此返回的也是一个 tuple
(2, 1)
Function 仍然只返回一个 object,这里返回的是包含两个 elements 的 tuple;caller 再通过 unpacking 把两个 elements 分别绑定给
quot和rem。因此这里返回 quot 和 rem 的时候发现同时都被创建了。此外,Python 内置的
divmod(x, y)也把 quotient 和 remainder 组合为 tuple 返回。所以是 caller name those values directly!!
Big Idea
Returning one object (a tuple) allows you to return multiple values (tuple elements), and unpacking lets the caller name those values directly.
9.3.5 You Try It:char_counts
Write a function that returns the number of vowels and consonants in a lowercase string.
def char_counts(s):
""" s is a string of lowercase alphabetic chars.
Returns a tuple whose first element is the number of vowels in s and whose second element is the number of consonants.
"""
# 可以直接写:
# num_vowels = 0
# num_consonants = 0
# 这一节可写:
(num_vowels, num_consonants) = (0, 0)
for char in s:
if char in "aeiou":
num_vowels += 1
else:
num_consonants += 1
return (num_vowels, num_consonants)
print(char_counts("hellomit")) # (3, 5)
在 specification 已保证 s 只包含 lowercase alphabetic characters 的前提下,非 vowel 的 character 就是 consonant。
tips: 如果允许 spaces、digits 或 punctuation,就应显式增加
elif char.isalpha(),否则这些 characters 也会被误计为 consonants。
9.4 Variable number of arguments:*args
另一件我们可以用 tuples 做的事就是创建这些接收可变数量的参数的函数(如我们之前在 tcl 语言中学到过的,有些没输入的数值就是默认的,等等)。因此,当我们定义函数的时候,基本上是告诉 python 我们期望它能够接收多少个参数。
- 像
min(4, 1)、min(4, 1, ..., args)等 built-in functions 可以接收 variable number of arguments。但这种函数的内部并不是 tuples(虽然它即使使用 tuples 作为对象也可以正常工作)。 - python 允许 自定义函数能在 parameter 前使用
*notation,把额外 positional arguments 收集起来:
def mean(*args):
total = 0
for value in args:
total += value
return total/len(args)
print(mean(1, 2, 3, 4, 5, 6)) # 3.5
只要你创建一个函数,他的参数设置中前面加了个 *;或者更具体来说,参数为 * 时(因为实际收集是 *),则 python 会将输入视为 tuples,然后在后台处理:
numbersis bound to a tuple of the supplied values- e.g.
mean(1, 2, 3, 4, 5, 6),这里意味着args对应元组(1, 2, 3, 4, 5, 6) - 调用后,local parameter
args会被视为一个 tuple,即绑定到 tuple(1, 2, 3, 4, 5, 6)。 - 事实上,名字
args只是 convention 惯例,真正产生收集行为的是符号*;但遵循这个命名能让读者立即识别这种 parameter。
p.s. 上面的 specification 应要求至少提供一个 number,否则
mean()会因为len(args) == 0而产生 division by zero。若要主动给出更清楚的错误,可以写为:
def mean(*args):
if len(args) == 0:
raise ValueError("mean requires at least one value")
return sum(args)/len(args)
此外,如果写成了 mean(arg),即如下情况,这时候当人们应用这个函数的时候,则要显式传入 explictly passing in ONLY ONE argument that is a tuples!!!
def mean(args):
total = 0
for value in args:
total += value
return total/len(args)
print(mean((1, 2, 3, 4, 5, 6))) # 3.5
# 注意不是 mean(1, 2, 3, 4, 5, 6),而是 mean((1, 2, 3, 4, 5, 6)),得显式传入,此外还利用到了 tuple 可以被 iterated over
9.5 Lists
列表事实上很多地方和 tuples 大差不差,有这么几点定义上的区别:
List(列表)也是 indexable ordered sequence of objects
- List 通常保存同类 homogenous objects,例如 all integers、all strings 或 all lists;
- Python 允许 mixed types,但同质 collection 往往更便于迭代和推理
Denoted by square brackets
[],而 tuples 则使用 parentheses()List 与 tuple 的关键差异是,List 是 mutable
- 可以替换特定位置的 element,也可以在后续操作中改变 list 的长度
- Remember tuples are immutable, i.e., you cannot change element values. List are mutable, you can change them directly.
9.5.1 List literals, indices, and ordering
a_list = [] # 创建一个 empty list
M = [1] # 创建一个仅包含一个元素的列表并不需要像 tuple 写 (1,) 多个额外的 comma,这是因为在 square brackets 中没有 operation precedence 的混淆
# 其他情况下和前面我们介绍的数组情况没多大差别
L = [2, 'a', 4, [1, 2]]
print([1, 2]+[3, 4]) # [1, 2, 3, 4]
print(len(L)) # 4; gives length of top level of tuple/list
print(L[0]) # 2
print(L[2]+1) # 5
print(L[3]) # [1, 2],这是一个 nested list
i = 2
print(L[i-1]) # 'a',因为 i-1 == 1
print(max([3, 5, 0])) # 5
与 tuple 一样,list 从 index 0 开始,也支持 negative indices、slicing、concatenation 和 nested indexing。
L[4] 会产生 IndexError。
List 的 mutability 可以通过 item assignment 直接看到:
L[1] = 'b'
print(L) # [2, 'b', 4, [1, 2]]
需要注意的是,这里没有创建一个替代 L 的完整 new list,而是让原 list 的 index 1 保存另一个 object reference;任何同时引用这个 list object 的 name 都会观察到变化,这也是下一讲 aliasing 问题的来源。
9.5.2 Iterating over a list
计算 list elements 的总和,可以按 index 遍历,因为 range(len(L)) 依次产生 0 到 len(L)-1,所以这些值正好是所有有效 indices:
L = [8, 3, 5]
total = 0
for i in range(len(L)):
total += L[i]
print(total) # 16
不过,如果 computation 只需要 element value,不需要 index,直接遍历 list 更自然(more pythonic),就像前面我们学过的遍历字符串里的字符一样,直接遍历列表中的元素:
total = 0
for value in L:
total += value
print(total) # 16
在第二种写法中,loop variable value 按顺序绑定到 8、3、5。给 variable 起能表达 element 含义的名字,通常比一律使用 i 更清楚;i 经常用于表示 integer index。
9.5.3 Capturing iteration in functions
把常见 iteration pattern 封装为 function:
def list_sum(L):
total = 0
for element in L:
total += element
return total
print(list_sum([1, 3, 5])) # 9
# 前面我们 tuple 处理是用 sum(*args),此时调用则为 sum(1,3,5); 或 sum(args),此时调用则为 sum((1,3,5))
如果 list 中保存 strings,也可以对每个 element 做适合其 type 的 operation,例如累加 string lengths:
def len_sum(L):
total = 0
for string in L:
total += len(string)
return total
print(len_sum(['ab', 'def', 'g'])) # 6

这两个 functions 的 loop structure 相同,但 element 上执行的 operation 不同。 由此也能回看 Lecture 8 的 abstraction:更进一步可以把 operation 抽象为 function argument。
9.5.4 You Try It:sum_and_prod
def sum_and_prod(L):
""" L is a list of numbers
Returns a tuple whose first value is the sum of all elements
in L and whose second value is the product of all elements
"""
total = 0
product = 1
for number in L:
total += number
product *= number
return (total, product)
print(sum_and_prod([2, 3, 4])) # (9, 24)
total 从 additive identity 0 开始,product 从 multiplicative identity 1 开始。这个 initialization 也自然规定了 empty list 的结果为 (0, 1);如果题目的 domain 不允许 empty list,应把 L is nonempty 写进 specification。
9.6 Summary
lambdaexpression 创建 anonymous function object,适合在 argument position 提供简短、一次性的 behavior;body 是一个 expression,并隐式返回其结果。- Tuple 和 list 都是 indexable ordered sequences,可以保存任意 objects,并支持 indexing、slicing、concatenation、
len()和 iteration。 - Tuple immutable,使用
();single-element tuple 必须写 comma。 - List mutable,使用
[]。 - Tuple unpacking 可以交换 variable bindings,也使 caller 能直接接收 function 返回 tuple 中的多个 values。
- Function 实际一次只返回一个 object;所谓“返回多个值”通常是返回一个 tuple 后再 unpack。
*args把 variable number of positional arguments 收集为 tuple。- 遍历 list 时,如果不需要 index,优先直接写
for element in L- 需要 index 或修改特定位置时再使用
range(len(L))或后续会学到的enumerate()。
- 需要 index 或修改特定位置时再使用
9.7 Supplement:Python sequences 的专业概念、惯用写法与复杂度
本节为 Lecture 9 主体后的补充,主要参考 Fluent Python: Clear, Concise, and Effective Programming, 2nd Edition Chapter 2 “An Array of Sequences” 与 Chapter 6 “Object References, Mutability, and Recycling”,并补充本讲相关的 CS 术语和 Python 惯用写法。
9.7.1 两种 sequence 分类方式
从 storage model 看,Python sequences 可以分为:
- Container sequence 保存对各个 Python objects 的 references,所以能够容纳不同 types,也能嵌套其他 containers;
list、tuple和collections.deque属于这一类。 - Flat sequence 直接在自己的 memory space 中紧凑保存同一种底层 value,而不是分别保存对任意 Python objects 的 references;
str、bytes和array.array是常见例子。它们通常更节省空间,但 element types 更受限制。
从 mutability 看,又可分为:
- Mutable sequence:例如
list、bytearray、array.array、collections.deque。 - Immutable sequence:例如
tuple、str、bytes。
这两个维度彼此独立。list 是 mutable container sequence,tuple 是 immutable container sequence,str 则是 immutable flat sequence。掌握这种 taxonomy(分类体系)后,可以把一个 sequence 上的知识迁移到其他 sequence types,同时避免把“能否容纳不同对象”和“自身能否修改”混为一谈。
9.7.2 Tuple 的双重角色:record 与 immutable list
把 tuple 只理解成 immutable list 并不完整。它还常被用作 record(记录):element 的 position 就相当于没有写出名字的 field。例如:
city_record = ('Tokyo', 2003, 32_450, 0.66, 8014)
city, year, population, change, area = city_record
作为 record 时,element 数量通常固定,order 具有语义;交换顺序会改变数据的含义。Unpacking 可以用有意义的 variable names 显示这些 fields,减少 record[0]、record[1] 等容易出错的 magic indices。如果 fields 较多、含义不明显,后续可以考虑 typing.NamedTuple、dataclass 或 class 来提供 field names。
作为 immutable list 时,tuple 表达“这个 sequence 的 element references 与长度不应改变”。这可以提升意图的清晰度;固定长度也让 tuple 通常比同长度 list 占用更少 memory。不过,不应仅为微小 performance 差异到处把 list 改成 tuple,首先应根据 data semantics 选择类型。
9.7.3 Tuple 是 relative immutability
Tuple 的 immutability 约束的是 tuple 自己保存的 references:这些 references 不能被替换或删除;如果其中一个 reference 指向 mutable object,该 object 的内部仍然可以变化:
t = (1, 2, [30, 40])
t[2].append(50)
print(t) # (1, 2, [30, 40, 50])
这里 t[2] 前后仍指向同一个 list object,tuple 的 storage 没有被 item assignment 改写,变化发生在 nested list 内部。因此“tuple immutable”不等于“由 tuple 可到达的整个 object graph 都不会变”。这种性质称为 relative immutability(相对不可变性)。
这也影响 hashability:只有当 tuple 的所有 elements 都可 hash 时,整个 tuple 才能作为 dict key 或 set element。
hash((1, 2, (3, 4))) # 合法
hash((1, 2, [3, 4])) # TypeError,因为 list unhashable
9.7.4 Iterable unpacking 与 * 的两个方向
更准确的术语是 iterable unpacking,因为右侧不必是 tuple,任何能依次产生合适数量 elements 的 iterable 都可以 unpack:
first, second, third = [10, 20, 30]
quotient, remainder = divmod(20, 8)
左侧可以用一个 starred target 收集 excess items,收集结果是 list:
first, *middle, last = range(5)
print(first) # 0
print(middle) # [1, 2, 3]
print(last) # 4
在 function definition 中,*args 是把许多 positional arguments pack 成一个 tuple;在 function call 中,*iterable 则把 iterable unpack 成多个 positional arguments:
values = (20, 8)
print(divmod(*values)) # 等价于 divmod(20, 8),得到 (2, 4)
因此,同一个 * syntax 的具体含义取决于所在位置:parameter list 中负责收集,argument list 中负责展开,assignment target 中负责吸收剩余 elements。
9.7.5 List comprehension:明确表达“构造新 list”
讲义中的 iteration 还可以写成 list comprehension(列表推导式)。它的目标总是根据 iterable 构造一个 new list:
symbols = '$¢£¥€¤'
codes = []
for symbol in symbols:
codes.append(ord(symbol))
codes = [ord(symbol) for symbol in symbols]
第二种写法把 mapping 意图集中表达为“对每个 symbol 计算 ord(symbol)”。也可以增加 filtering condition:
squares_of_odd = [n*n for n in range(10) if n%2 == 1]
print(squares_of_odd) # [1, 9, 25, 49, 81]
List comprehension 应用于需要所生成 list 的场景;不要仅为了 print()、修改外部 object 等 side effects 使用它。若 expression 和 conditions 复杂到需要多行解释,普通 for loop 通常更易读。
9.7.6 Equality、identity、alias 与 shallow copy
Assignment 绑定 object reference,并不会自动复制 collection:
a = [1, 2, 3]
b = a
b[0] = 99
print(a) # [99, 2, 3]
a 与 b 是 aliases,指向同一个 list object。== 比较 values 是否相等,is 比较是否为同一个 object:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == c) # True,values equal
print(a is c) # False,different objects
print(a is b) # True,same object
最常见的 identity check 是 value is None 或 value is not None;一般内容比较应使用 ==。
构造 list(original)、调用 original.copy() 或 slicing original[:] 会创建 outer list 的 shallow copy(浅拷贝)。Outer objects 不同,但 nested mutable elements 仍可能共享:
original = [1, [2, 3]]
cloned = original.copy()
cloned.append(4) # 只改变 cloned 的 outer list
cloned[1].append(99) # inner list 是共享对象,original 也能观察到
print(original) # [1, [2, 3, 99]]
print(cloned) # [1, [2, 3, 99], 4]
如果确实需要递归复制 nested objects,可以研究 copy.deepcopy();但 deep copy 的 cost 更高,而且共享关系本身有时正是 data model 的一部分,因此应先明确 ownership 和 mutation policy。
9.7.7 Mutable parameters、side effects 与安全默认值
Python function parameters 接收到 argument object 的 references。对 local parameter name 重新绑定不会改变 caller 的 name,但通过 method 修改一个 shared mutable object 会产生 caller 可见的 side effect:
def add_sample(samples, value):
samples.append(value)
data = [1, 2]
add_sample(data, 3)
print(data) # [1, 2, 3]
这种行为可以是设计目标,但应在 function specification 中明确说明。如果 caller 不应被修改,可以在函数中先复制 input,或构造并 return new list。
不要用 mutable object 作为普通 default argument,因为 default object 在 def 执行时创建,后续 calls 会共享它:
def collect(value, result=[]): # 容易产生跨调用共享状态的 bug
result.append(value)
return result
常见安全写法使用 None 作为 sentinel,并为每次未提供 argument 的 call 新建 list:
def collect(value, result=None):
if result is None:
result = []
result.append(value)
return result
9.7.8 常用 sequence operations 的复杂度
用 Big-O notation 看,对于长度为 n 的 built-in list 或 tuple:
seq[i]通过 index 直接定位,平均为 O(1)。len(seq)为 O(1),因为 sequence object 保存了长度信息。x in seq在最坏情况下需要逐个比较,为 O(n)。- 一般的
seq[a:b]需要产生包含k个 elements 的 slice,时间为 O(k);immutable tuple 的完整 slice 等特殊情况可能被 implementation 优化为复用原对象。 left+right需要复制两侧 references 到 new sequence,为 O(len(left)+len(right))。- List 的
append()通常是 amortized O(1)(摊还常数时间);偶尔扩容会复制底层 reference array,但预留空间让许多次 append 的平均 cost 保持常数级。
这些复杂度说明了一个常见 writing rule:如果目标是逐步构造 list,连续 append() 通常比在 loop 中反复执行 result = result+[item] 更合适;后者每轮都创建并复制一个越来越长的 new list,累计可能达到 O(n²)。
9.7.9 Common design rules
- 固定、位置具有语义的一组 fields 可以用 tuple,并尽量立即 unpack 成有意义的 names;需要频繁修改长度或 elements 的 collection 使用 list。
- Function 返回几个彼此相关的结果时可以 return tuple;fields 较多或 public API 长期维护时,使用 named record 能降低顺序写错的风险。
- 只需 element value 时写
for element in sequence;确实需要 index 时可用for index, element in enumerate(sequence),比手动组合range(len(sequence))与 indexing 更清楚。 - 简单 transformation/filtering 可以使用 list comprehension;复杂 control flow、side effects 或多步 debugging 使用普通 loop。
- 传递 mutable collection 前先明确 ownership:callee 是否有权原地修改,还是应 return new object。Specification 应把可观察的 mutation 写清楚。
lambda适合简短的 callback 或 sorting key,例如sorted(words, key=lambda word: len(word));需要复用、type annotation、docstring 或多步逻辑时使用def。
Lecture 10: Lists and Mutability
10.1 Lists recap and mutability
上一讲介绍了 list 和 tuple 的共同操作:indexing、slicing、concatenation 和 iteration。 本讲我们将进一步讨论并关注 mutability(可变性),我们将着重强调他们的概念、语法:
- 修改 list 中的内容时,原 list object 可以继续存在,变化的是它保存的 elements。
10.1.1 Indices and ordering in lists
a_list = [] # create an empty list
L = [2, 'a', 4, [1, 2]]
print(len(L)) # 4,统计 outer list 的 elements
print(L[0]) # 2
print(L[3]) # [1, 2],整个 inner list 是一个 element
print([2, 'a']+[5, 6]) # [2, 'a', 5, 6]
print(max([3, 5, 0])) # 5
print(L[1:3]) # ['a', 4]
for element in L: # loop variable becomes each element in L
print(element) # 依次打印 2、a、4、[1, 2]
L[3] = 10
print(L) # mutate L by changing an element [2, 'a', 4, 10]
L[3] = 10 把 index 3 处保存的 reference 替换为指向 integer 10 的 reference;outer list 的长度仍是 4。
这也说明 list 中某个位置的 element type 可以改变。
10.1.2 Mutation vs. rebinding
下面我们将讨论在内存的变化中意味着什么。
# remenber: Lists are **mutable**!
# Assigning to an element at an index changes the value
L = [2, 4, 3]
L[1] = 5
print(L) # L is now [2, 5, 3]; note this is the same object L!
t = (2, 4, 3)
t = (2, 5, 3)
print(t) # (2, 5, 3)
两段代码最后显示的内容相似,但 operation 不同:
L[1] = 5是 mutation:改变原 list object 的内容,nameL仍绑定到该 object。这一点与 strings 和 tuples 都有十分的不同
t = (2, 5, 3)是 rebinding:让 namet指向另一个 tuple;原来的(2, 4, 3)没有被修改。如果还有其他 reference 指向它,它依然可被访问。
总结为两句话:
- Making L by mutating an element vs.
- Making t by creating a new object
因此,immutable 描述的是 object 的性质,不限制一个 variable name 以后绑定到别的 object。而 mutable 描述的是改变 object 本身,this does allow us to go memory and literally change that objects. 分析程序时,需要同时追踪 name 指向哪个 object 和 该 object 的内容是什么。
10.2 Operation on lists
这一小节我们将讲述 List methods、append() 与 side effects。
拿到 list object,由于他的 mutability,我们可以对此进行更多的操作。例如在列表尾部进行增添。
10.2.1 append() mutates the list and returns None
L.append(element)- 上面的
L和element是你所指定的 object append实际上就是函数的名字,类似于使用.func(*args)- 作用:在 list 尾部加入一个 element,并原地修改 L
- 上面的
L = [2, 1, 3]
L.append(5)
print(L) # [2, 1, 3, 5]
这里有必要提到一个神奇的现象,即 side effect。下面调用 append() 是为了体现 side effect(副作用),即修改 list 的状态。
append() 的 return value 是 None,因此不要用它的返回值覆盖 list variable:
L = [2, 1, 3]
L.append(5)
print(L) # 返回:[2, 1, 3, 5]
print(L.append(5)) # 返回: None!!!
L = L.append(5) # 容易写错的一行
print(L) # 返回: None!!!
按照 assignment 的执行顺序理解最后一行:先执行右侧 L.append(5),把原 list 改成 [2, 1, 3, 5, 5];
随后这个函数调用 call 返回 None,左侧 assignment 再让 L 绑定到 None。原 list 已经被修改,但 name L 不再指向它。
不难注意到,如果我们不想动原先的 L,直接 append 即可,若再另外赋值则会引来 side effect.
Therefore, append is used strictly for its side effect.
Big Idea
Some methods mutate a list and return None. We call them for their side effects,通常直接写 L.append(value),无需保存 call 的 return value。
Sometimes, we use these functions for their side effect.
10.2.2 You Try It:trace nested lists
What is the value of L1, L2, L3 and L at the end?
L1 = ['re']
L2 = ['mi']
L3 = ['do']
L4 = L1+L2
L3.append(L4)
L = L1.append(L3)
L4 = L1+L2创建新的 outer list['re', 'mi'];L3.append(L4)把整个L4作为一个 element 加入L3,因此 L3 为['do', ['re', 'mi']],而不是['do', 're', 'mi'],要十分小心!!- 最后
L1.append(L3)又把整个L3加入L1,一开始 mutateL1为['re', ['do', ['re', 'mi']]]并返回None。
print(L1) # ['re', ['do', ['re', 'mi']]]
print(L2) # ['mi']
print(L3) # ['do', ['re', 'mi']]
print(L4) # ['re', 'mi']
print(L) # None
注意 append() 不会展开传入的 list,也不会递归复制它:L1[1] is L3、L3[1] is L4 都是 True。
因此这里建立了 nested references (嵌套引用);L4 则是先前通过 + 得到的独立 outer list,不会随着后来 L1 的增长自动增长。
10.2.3 What is the dot:method call

Python objects 具有 data,也有由其 type 提供的 operations。L.append(5) 中的 dot . 用于访问 object 的 attribute;这里取得的是可调用的 method(方法),随后 () 发起调用:
L = [2, 1, 3]
L.append(5)
对于 built-in list,上述 method call 也可以表达为 list.append(L, 5):操作需要知道被修改的 list 和要追加的 value,而 L.append(5) 已经通过 dot 左侧的 L 指定了前者。这个接收 operation 的 object 也称为 receiver(接收者)。
L.append 只是取得 method object;L.append(5) 才执行操作。类似地,即便 method 不接收额外 arguments,也要写 L.sort()、L.clear() 才会调用。
10.2.4 You Try It:make_ordered_list
返回按顺序包含从
0到n(inclusive)的全部 integers 的 list。
def make_ordered_list(n):
""" n is a positive int
Returns a list of all ints from 0 to n inclusive, in order
"""
result = []
for number in range(n+1):
result.append(number)
return result
print(make_ordered_list(5)) # [0, 1, 2, 3, 4, 5]
这里每次 append() 返回 None,但 function 最后显式 return result,所以 make_ordered_list() 返回的是构造好的 list。日常代码也可以用 list(range(n+1)) 完成同样的工作;课堂版本主要练习“初始化空列表 → 逐项加入 → 返回结果”的 pattern。
10.2.5 You Try It:remove_elem
返回一个 new list,保留原顺序,但不包含任何等于
e的 element。
def remove_elem(L, e):
""" L is a list
Returns a new list with the elements of L in the same order,
excluding every element equal to e. Does not mutate L.
"""
result = []
for element in L:
if element != e:
result.append(element)
return result
L = [1, 2, 2, 2]
print(remove_elem(L, 2)) # [1]
print(L) # [1, 2, 2, 2]
这里通过 condition 筛选需要保留的 elements,属于 filtering(过滤)。只修改新建的 result,因此不会改变 caller 提供的 L,也不会因为在遍历过程中删除元素而改变后续 indices。
10.3 Converting between strings and lists
10.3.1 list(s) and s.split()
list(s) 按 character 拆开 string,spaces 也会成为独立 elements;s.split(sep) 则按 separator 拆出 substrings:
s = "I<3 cs &u?"
print(list(s))
# ['I', '<', '3', ' ', 'c', 's', ' ', '&', 'u', '?']
print(s.split(' ')) # ['I<3', 'cs', '&u?']
print(s.split('<')) # ['I', '3 cs &u?']
两种操作都会返回 new list,原 string 保持原值。split() 的 separator 可以包含多个 characters;省略参数时按 whitespace(空白字符,包括空格、tab、newline 等)拆分,并把连续 whitespace 当成一组:
print(" a b ".split()) # ['a', 'b']
print(" a b ".split(' ')) # ['', '', 'a', '', 'b', '', '']
print("".split()) # []
print("".split(' ')) # ['']
split() 与 split(' ') 的边界行为不同:指定 separator 时,相邻 separators 之间可以产生 empty string;不指定时会跳过开头、结尾的 whitespace,并合并连续 whitespace。
10.3.2 separator.join(strings)
join() 把多个 strings 连接成一个 string,dot 左侧的 string 是放在相邻 elements 之间的 separator:
L = ['a', 'b', 'c']
print(''.join(L)) # abc
print('_'.join(L)) # a_b_c
print(' / '.join(L)) # a / b / c
Separator 只插在相邻 elements 之间,结果首尾不会自动多出 separator。传入 iterable 中的每个 element 都必须是 string,join() 不会自动对 numbers 调用 str():
# ''.join([1, 2, 3]) # TypeError,elements 不是 strings
print(''.join(['1', '2', '3'])) # 123
print(''.join(str(n) for n in [1, 2, 3])) # 123,先显式转换
10.3.3 You Try It:count_words
def count_words(sen):
""" sen is a string representing a sentence
Returns the number of whitespace-separated words in sen
"""
words = sen.split()
return len(words)
print(count_words("Hello it's me")) # 3
print(count_words(" Hello it's me ")) # 3
print(count_words("")) # 0
对于讲义给出的 single-space example,sen.split(' ') 也会得到 3;这里使用无参数 split(),明确把 specification 扩展为按 whitespace 分词,以处理连续空格和空句子。它只是按分隔符计数,it's 仍是一个 word,punctuation 也不会被自动去除。
10.4 Sorting and reversing lists
10.4.1 sort()、reverse() and sorted()
这些操作需要区分 是否修改原 object 和 call 返回什么:
| Operation | 对原 list 的影响 | Return value |
|---|---|---|
L.append(x) | 在尾部加入一个 element | None |
L.sort() | 原地排序 | None |
L.reverse() | 原地反转当前顺序 | None |
sorted(L) | 不修改 L,构造排好序的 new list | New list |
reverse() 只反转已有顺序,不比较 elements 的大小。因此对 [4, 2, 7] 调用 reverse() 得到 [7, 2, 4],并不等于 descending sort。
10.4.2 Trace the objects and return values
L = [9, 6, 0, 3]
L.append(5)
print(L) # [9, 6, 0, 3, 5]
a = sorted(L)
print(a) # [0, 3, 5, 6, 9]
print(L) # [9, 6, 0, 3, 5]
b = L.sort()
print(L) # [0, 3, 5, 6, 9]
print(b) # None
L.reverse()
print(L) # [9, 6, 5, 3, 0]
print(a) # [0, 3, 5, 6, 9]
a 与 L 是两个不同的 outer list objects;之后改变 L 的排列顺序不会重新排列 a。b = L.sort() 则把 None 绑定给 b,没有得到另一个 sorted list。若目的只是给 L 排序,直接写 L.sort() 即可。
10.4.3 You Try It:sort_words
def sort_words(sen):
""" sen is a string representing a sentence
Returns its whitespace-separated words in sorted order
"""
words = sen.split()
return sorted(words)
print(sort_words("look at this photograph"))
# ['at', 'look', 'photograph', 'this']
也可以先对 function 内部新建的 words 原地排序,再返回它:
def sort_words(sen):
words = sen.split()
words.sort()
return words
不要写 return words.sort(),那会返回 None。两种正确版本都满足 specification;这里原地修改的是函数内部由 split() 新建的 list,不会修改作为 input 的 string。
对于讲义里的 lowercase English words,默认排序符合通常的字母顺序;一般 Python string comparison 按 Unicode code points 做 lexicographic comparison(字典序比较),大小写和标点都会影响结果,并不自动采用自然语言词典规则。
10.5 Writing functions that mutate inputs
自定义函数也可以修改 caller 传入的 mutable object。例如,把 list 中的每个 number 平方并写回原位置。
10.5.1 Why assigning to the loop variable is not enough
L = [2, 3, 4]
for element in L:
element = element**2
print(L) # [2, 3, 4]
循环中 element 是一个 name,每次被绑定到 list 当前的 element。element = element**2 只重新绑定这个 loop variable,没有对 L 的任何位置执行 assignment。要替换 list 中的 numbers,必须把赋值目标写成 L[index]。
10.5.2 square_list:iterate over indices
def square_list(L):
""" L is a list of numbers
Mutates L by squaring every element. Returns None.
"""
for i in range(len(L)):
L[i] = L[i]**2
Lin = [2, 3, 4]
print("before fcn call:", Lin) # before fcn call: [2, 3, 4]
square_list(Lin)
print("after fcn call:", Lin) # after fcn call: [4, 9, 16]
Function 的 local parameter L 与 caller 中的 Lin 引用同一个 list object,所以 L[i] = ... 的结果在 caller 中也能看到。每轮的状态为:
i = 0: [2, 3, 4] -> [4, 3, 4]
i = 1: [4, 3, 4] -> [4, 9, 4]
i = 2: [4, 9, 4] -> [4, 9, 16]
square_list() 没有显式 return,因此返回 None。直接调用 square_list(Lin) 即可;如果写 Lin = square_list(Lin),会在完成 mutation 后把 caller 的 Lin 重新绑定到 None。
10.5.3 Other ways to obtain the index
讲义还列出两种方法:在循环外初始化 counter、每轮手动增加;或者用 enumerate() 同时取得 index 与 element。后者更常见:
def square_list(L):
for i, element in enumerate(L):
L[i] = element**2
enumerate(L) 依次提供 (0, L[0])、(1, L[1]) 等 pairs,循环中的 i, element 对它们进行 unpacking。这里仅替换当前位置,list 长度不变,因此可以按顺序完成整个 traversal。
Big Idea
需要替换 list 中的 element 时,对 L[i] 赋值;需要修改 input object 的函数,应在 specification 中说明 mutation。 range(len(L)) 和 enumerate(L) 都能提供写回所需的 index。典型的原地修改函数返回 None,但这属于 API convention,并非语法限制。
10.6 Mutation during iteration:tricky examples 1 and 2
Mutation 可以让我们只更新很长 list 中的一个 record,无需构造完整的新列表。但当 loop 正在遍历 list 时,改变其长度会影响后续访问位置。讲义依次比较“遍历固定 indices”“遍历正在增长的 list”和“遍历时重新绑定 name”三种情况。
10.6.1 Tricky example 1:range(len(L)) and append()
L = [1, 2, 3, 4]
for i in range(len(L)):
L.append(i)
print(L)
# [1, 2, 3, 4, 0]
# [1, 2, 3, 4, 0, 1]
# [1, 2, 3, 4, 0, 1, 2]
# [1, 2, 3, 4, 0, 1, 2, 3]
进入 loop 时,len(L) 求值为 4,所以 iterable expression 得到的是 range(4)。之后 i 依次取 0、1、2、3;即便 loop body 把 L 变长,已经创建的 range 也不会重新计算 len(L)。因此循环执行 4 次。
range 是一种 immutable sequence,可用少量参数描述 arithmetic progression(等差数列);它既不是 tuple,也不是一次性 iterator。for 从 range 取得 iterator,按需取出各个 integers:
print(list(range(4))) # [0, 1, 2, 3]
print(list(range(2, 9, 2))) # [2, 4, 6, 8]
这里把 range 转成 list 只是为了显示它所表示的 values;通常直接迭代 range,无需先构造 list。
10.6.2 Tricky example 2:iterate over the growing list
# 以下是不会自行结束的示例,不要直接运行完整循环
L = [1, 2, 3, 4]
i = 0
for element in L:
L.append(i)
i += 1
print(L)
前四轮输出和上一个例子相同,但这次 loop 直接使用 L 的 list iterator。它按位置继续读取同一个 list object,不会在创建 iterator 时把 elements 复制成一份固定 snapshot。
每轮读取一个 element 的同时又追加一个,iterator 到达原来的末尾后仍能读到新增 elements;因此 loop 不会正常耗尽,list 会持续增长,直到人为中断或遇到资源限制。关键差异在于:前一个 loop 消耗固定的 range(4),这个 loop 消耗正在增长的 list。
可以加上明确的 iteration limit 观察前几步,但这种 limit 只适合演示;实际程序通常应遍历一份 snapshot,或把新增结果保存在另一个 list 中。
10.7 Combining lists:+、extend() and rebinding
10.7.1 Concatenation creates a new list
L1 = [2, 1, 3]
L2 = [4, 5, 6]
L3 = L1+L2
print(L1) # [2, 1, 3]
print(L2) # [4, 5, 6]
print(L3) # [2, 1, 3, 4, 5, 6]
+ 创建 new outer list,并把两个 operands 中的 element references 按顺序放入其中。原来的 L1、L2 都不变。讲义的 “copies” 应理解为复制 element references,不能据此推断 nested mutable objects 也被递归复制。
10.7.2 extend() mutates the receiver
L1.extend([0, 6])
print(L1) # [2, 1, 3, 0, 6]
print(L3) # [2, 1, 3, 4, 5, 6]
L2.extend([[1, 2], [3, 4]])
print(L2) # [4, 5, 6, [1, 2], [3, 4]]
extend(iterable) 把 iterable 产生的各个 elements 依次加入 receiver,修改原 list 并返回 None。第二个调用加入了 两个 elements,它们分别是 [1, 2] 和 [3, 4];extend() 不会递归 flatten nested lists。
与 append() 对比时,重点看把 argument 整体当成一个 element,还是逐项加入:
a = [1, 2]
b = [1, 2]
a.append([3, 4])
b.extend([3, 4])
print(a) # [1, 2, [3, 4]]
print(b) # [1, 2, 3, 4]
10.7.3 Tricky example 3:L = L + L inside a loop
L = [1, 2, 3, 4]
for element in L:
L = L+L
print(L)
这段代码也让 L 越来越长,但循环只执行 4 次。进入 for 时,Python 对最初的 [1, 2, 3, 4] 取得 iterator;之后每轮 L+L 创建 new list,再由 assignment 把 name L 绑定到这个结果。Iterator 始终遍历最初那个 list object,而 name L 已经指向其他 objects。
用每轮的 element、长度与重复次数代替很长的打印结果,可以清楚地追踪:
| Iteration | element 的值 | 本轮 assignment 后的 len(L) | 新 L 的内容 |
|---|---|---|---|
| 1 | 1 | 8 | [1, 2, 3, 4] 重复 2 次 |
| 2 | 2 | 16 | [1, 2, 3, 4] 重复 4 次 |
| 3 | 3 | 32 | [1, 2, 3, 4] 重复 8 次 |
| 4 | 4 | 64 | [1, 2, 3, 4] 重复 16 次 |
每一轮右侧的两个 L 都解析为当前 name L 指向的 list,因此长度不断翻倍;但原始迭代对象长度始终为 4,第四个 element 取完后 loop 结束。
Big Idea
判断 mutation during iteration 的行为,要问两个问题:iterator 正在读取哪个 object?loop body 修改的是这个 object,还是只重新绑定了某个 name? for 在开始时取得 iterator,后续不会因为 iterable variable 重新赋值就改用另一个 iterator。
10.8 Emptying a list and checking object identity
10.8.1 clear() preserves identity
L.clear() 删除原 list 的全部 elements,保留该 list object:
L = [4, 5, 6]
original_id = id(L)
L.append(8)
print(id(L) == original_id) # True
L.clear()
print(L) # []
print(id(L) == original_id) # True
id(obj) 返回表示 object identity 的 integer,在该 object 存活期间保持不变。具体数值取决于运行环境,因此这里比较前后是否相等,无需记住某个地址值。
10.8.2 L = [] rebinds the name
L = [4, 5, 6]
original = L
L = []
print(L) # []
print(original) # [4, 5, 6]
print(L is original) # False
L = [] 创建新空 list,再把 L 绑定到它;original 仍引用原来的 list。与之比较:
L = [4, 5, 6]
original = L
L.clear()
print(original) # []
print(L is original) # True
如果其他代码也持有该 list 的 reference,clear() 的影响会被它们看到,单独重新绑定 L 则不会更新它们的 binding。CPython 中 id() 通常对应对象内存地址,但 Python 保证的是 lifetime 内的 identity;已结束生命周期的对象,其 ID 数值以后可能被复用。
10.9 Summary
- List 和 tuple 都可以组织数据并支持 iterative functions;tuple 的 references 固定,list 的内容和长度可以改变。
- Mutation 改变 object 的状态,rebinding 改变 name 与 object 的绑定关系;immutable object 也可以被 variable 的新 binding 替换。
append()、extend()、sort()、reverse()、clear()原地修改 list,并返回None;+和sorted()则产生 new list。append(x)把 x 整体加入,extend(iterable)逐项加入;这些操作都不会自动递归复制 nested objects。list(s)得到 character list,split()得到按 separator 划分的 strings,separator.join(strings)把 strings 连接起来。- 自定义函数可以修改 caller 传入的 list;替换某个位置应对
L[i]赋值,仅重新绑定 loop variable 不会写回 list。 - 遍历中修改 list 的长度需要特别小心:
range(len(L))的范围在进入 loop 时已确定,list iterator 则继续访问它所引用的 list object。重新绑定 L 不会更换已有 iterator 的来源。 clear()把同一个 list 清空;L = []把 L 绑定到新 list。is检查 object identity,==检查 values。- Tuple 常用于固定结构的数据,例如
(latitude, longitude);list 适合动态维护的数据,例如最近观看的影片列表。
10.10 Supplement:in-place operations、sorting 与 shared references
本节主要参考 Fluent Python: Clear, Concise, and Effective Programming, 2nd Edition Chapter 2 “An Array of Sequences” 中的 “Assigning to Slices”“Building Lists of Lists”“Augmented Assignment with Sequences”“list.sort Versus the sorted Built-In”(书内页码 pp. 50–58),以及 Chapter 6 “Object References, Mutability, and Recycling” 的 object references 与 parameter passing 相关小节。Lecture 9 Supplement 已介绍 shallow copy 和 mutable defaults,本节结合本讲 operations 进一步说明其实际影响。
10.10.1 In-place operation 与 API convention
In-place operation(原地操作) 表示通过修改现有 object 来完成任务,receiver 的 identity 保持不变。它不保证底层完全不分配新 memory:例如 list 在 append() 时可能扩充内部 reference array,但 list object 仍是同一个。
Python 的常见 convention 是:仅为 mutation 而设计的 methods 返回 None,让 caller 知道结果已反映在 receiver 上。所以不能把这些调用串成 L.sort().reverse();第一个 call 返回 None,后面的 .reverse() 会试图从 None 上取得 method。
这并非“有 mutation 就必定返回 None”的普遍规则。例如 L.pop() 同时移除并返回一个 element;自己定义的函数也可以修改 input 后再返回某个结果。判断方法行为应同时阅读 mutation contract 与 return-value contract。此外,side effect 的范围更广,print()、写文件等也是 side effects,并不都表现为修改 input。
10.10.2 += 与 L = L + other 的 identity 差异
对于 built-in list,+= 通常表达 in-place extension,作用类似 extend();这和 L = L+other 的 new-list construction 不同:
a = [1, 2]
alias = a
a += [3]
print(a) # [1, 2, 3]
print(alias) # [1, 2, 3]
print(a is alias) # True
a = [1, 2]
alias = a
a = a+[3]
print(a) # [1, 2, 3]
print(alias) # [1, 2]
print(a is alias) # False
Python object model 通过 __iadd__ 支持 in-place addition;没有相应实现时,才会回退到普通 addition 等机制。Tuple 无法被原地扩展,所以 tuple 的 += 会把结果 tuple 重新绑定给 variable。
因此不能把所有类型的 a += b 都机械理解为 a = a+b。特别是本讲 tricky example 3 中,如果把 L = L+L 改成 list 的 L += L,就会增长 iterator 正在遍历的原 list,失去原先的四次循环上限,并迅速耗尽 memory;不应直接运行这种改写。
10.10.3 Slice assignment:保留 list identity 的批量更新
Slice 出现在 expression 中时用于读取;出现在 assignment 左侧时,可以替换原 list 的一段内容:
L = [0, 1, 2, 3, 4]
alias = L
L[1:4] = [10, 20]
print(L) # [0, 10, 20, 4]
print(alias) # [0, 10, 20, 4]
print(L is alias) # True
普通 slice assignment 的 replacement 可以与被替换部分长度不同;右侧必须是 iterable。完整 slice L[:] 可以用于批量更新所有内容,因此 filtering 有两种不同的接口选择:
values = [1, 2, 2, 3]
filtered = [x for x in values if x != 2]
print(values) # [1, 2, 2, 3]
print(filtered) # [1, 3]
alias = values
values[:] = [x for x in values if x != 2]
print(alias) # [1, 3]
print(values is alias) # True
第二种写法先完整计算右侧的 new list,再把结果 references 写回原 list,因此不会一边遍历一边删除当前来源中的 elements。它既保留了 values 的 identity,也让已有 aliases 观察到过滤结果;代价是需要一份暂存结果。这里的 slice assignment 应放在 traversal 完成之后,若放进正在遍历同一 list 的 loop 中,仍可能影响 iteration。
10.10.4 key、reverse and stable sorting
list.sort() 与 sorted() 都接受 key 和 reverse keyword arguments。key 是一个接收单个 element 的 callable,排序时比较它产生的 key;reverse=True 表示按 key 降序排列:
words = ['pear', 'fig', 'plum', 'apple']
print(sorted(words, key=len))
# ['fig', 'pear', 'plum', 'apple']
print(sorted(words, key=len, reverse=True))
# ['apple', 'pear', 'plum', 'fig']
Python sorting 是 stable(稳定的):当两个 elements 的 comparison keys 相等时,它们在 input 中的相对顺序会保留。上例 pear 和 plum 长度都为 4,升序、降序的结果都让 pear 位于 plum 前面。
因此 sorted(words, key=len, reverse=True) 并不总是等于“先按长度升序,再把整个结果 reverse”;后者会把 equal-key group 内部的顺序也翻转。
records = [('B', 90), ('A', 90), ('C', 75)]
ordered = sorted(records, key=lambda record: record[1], reverse=True)
print(ordered) # [('B', 90), ('A', 90), ('C', 75)]
这体现了 Lecture 8/9 的 higher-order function:排序过程复用一个 algorithm,通过传入不同 key functions 决定比较规则。sorted() 也可接收 tuple、string 或其他 iterable,返回值始终是 new list;key 产生的值用于比较,不会把原 elements 替换为这些 key values。
10.10.5 Repeating nested lists repeats references
List multiplication 也会复制 element references,所以构造二维 list 时需要留意 inner objects 是否独立:
bad = [[0]*3]*3
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
print(bad[0] is bad[1]) # True
[0]*3 先创建一个 row,外层 *3 把对同一个 row object 的 reference 重复三次。对其中一行做 mutation,就能通过另外两个 references 看到同一变化。
如果希望每一行独立,应在每轮 iteration 中创建新 row:
good = [[0]*3 for _ in range(3)]
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
print(good[0] is good[1]) # False
这里 _ 是“这个 loop variable 不需要使用”的命名 convention。内层 [0]*3 可以安全共享 immutable integer 0 的 references;之后 good[0][0] = 1 替换的是某个 row 中的 slot,不会修改 integer 0。
Lecture 9.7.6 的 shallow copy 也有相同边界:bad.copy() 只复制 outer list,不能使共享的 rows 变成独立对象。即使 deepcopy(bad) 通常也会保留副本内部原有的共享关系;要构造独立 rows,应从一开始按上面的 comprehension 创建。
10.10.6 Call by sharing 与 function contract
《Fluent Python》用 call by sharing(共享传参) 描述 Python 的 argument passing:function parameter 得到对 argument object 的 reference。由此可以直接解释两种“清空输入”的差异:
def rebind(items):
items = []
def empty_in_place(items):
items.clear()
data = [1, 2, 3]
rebind(data)
print(data) # [1, 2, 3]
empty_in_place(data)
print(data) # []
rebind() 修改 local name 的 binding;empty_in_place() 修改 caller 与 callee 共享的 list。若接口承诺保留 input,可以使用 sorted(input)、comprehension,或者先做合适的 copy。这里需要明确 ownership(谁负责管理对象) 与 mutation contract(是否允许改变 caller 可见的状态),不能仅从 variable name 判断对象是否属于当前函数。
需要默认空 list 时,继续遵循 Lecture 9.7.7 的 None sentinel 写法,让每次需要默认值的 call 创建新 list;default argument 中直接写 [] 会让不同 calls 共享同一个 mutable default。
10.10.7 Common design rules
- 读 method specification 时同时确认 receiver 是否改变、return value 是什么;
None也是一个正常的 return value。 - 需要固定 snapshot 的 traversal 时,可遍历
L.copy();需要筛选出新结果时,可用 comprehension。Shallow snapshot 固定 outer elements 的排列,不保证 nested mutable objects 也被冻结。 range(len(L))只固定 indices 范围,不复制 L 的内容;若 loop 内删除 elements,后续 indices 仍可能失效。它不是所有 mutation-during-iteration 问题的通用解决方案。- 大量逐项构造 list 时优先使用
append()或合适的 comprehension;反复result = result+[item]会重复复制越来越长的 outer list,性能分析见 Lecture 9.7.8。 - 当多个 components 共享同一个 list 时,
clear()、slice assignment、+=会影响所有持有该 object 的引用者;重新绑定某个 local name 只改变该 binding。 - Debugging 时先画 name-to-object references,再追踪 iterator 的来源和每轮 mutation;这比只观察
print()出来的 values 更容易发现共享状态与终止条件的问题。
Appendix 1: Python tricks in vscode
- Toggle Line Comment,也就是“切换行注释”。在 VS Code 里,你可以选中一大段代码后,用快捷键批量取消注释。
- Windows:
/ - Linux:
Ctrl + / - macOS:
Command + /事实上,这个技巧在许多的文本编辑器里一般也会有。
- 如何在 python 中进行
cos()之类的函数的计算呢?
cos()不是 python 中的内置函数,因此它属于标准库中的math模块,因此需要先导入import math。这个知识点我们在 第5.1.2.1 曾经介绍过。
有几点需要注意的是:
- 无论下面利用到哪个方法,都要先
import math来启动标准库中的math模块,不过你也可以通过from math import cos, radians的方法直接导入所需的函数 math.cos()接收的是弧度,不是角度math.radians()可以接收角度,随后转化为弧度- 另一种角度转化为弧度的算法就是利用解析式【x 为某个我们已经赋值的角度】
(x/180)*pi,然而对于 pi 的值的引入也需要用到math.pi,即实际中的式子为(x/180)*math.pi
实际例子:0.01594/(cos(103.6/180*pi)*0.08724)
法1: 直接解析式算成弧度
import math
result = 0.01594 / (
math.cos(103.6 / 180 * math.pi) * 0.08724
)
法2: 借助 math.radians(),更简洁!
import math
# 第一行也可以只导入所需要的函数:
# from math import cos, radians
angle = math.radians(103.6)
result = 0.01594 / (math.cos(angle) * 0.08724)