{ "cells": [ { "cell_type": "markdown", "id": "cf04d555", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 聪明办法学 Python 2nd Edition\n", "## Chapter 3 变量与函数 Variables and Functions\n", "---\n", "聪明办法学 Python 教学团队\n", "\n", "

learn.python.the.smart.way@gmail.com

" ] }, { "cell_type": "markdown", "id": "52eb108d", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 变量 Variables\n", "\n", "> A variable is a named value that references or stores a piece of data.\n", "\n", "- 变量是一个**名字**,它所指代的是一段数据\n", "- 使用 `=` 来对这段数据的区域进行**赋值**" ] }, { "cell_type": "code", "execution_count": 7, "id": "de02b297", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:24:31.038253Z", "start_time": "2023-08-12T12:24:31.026210Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "x = 5" ] }, { "cell_type": "code", "execution_count": 8, "id": "98d2e95d", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:24:32.338555Z", "start_time": "2023-08-12T12:24:32.318722Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "print(x)" ] }, { "cell_type": "code", "execution_count": 9, "id": "aeb8757d", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:24:35.503312Z", "start_time": "2023-08-12T12:24:35.484439Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n" ] } ], "source": [ "print(x*2)" ] }, { "cell_type": "markdown", "id": "50cb960e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- 新的值会**覆盖**掉旧的值\n", "- 新值的数据类型不必与旧值相同" ] }, { "cell_type": "code", "execution_count": 10, "id": "8259c68b", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:26:26.571537Z", "start_time": "2023-08-12T12:26:26.558650Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "y = 10\n", "print(y - 2)" ] }, { "cell_type": "code", "execution_count": 11, "id": "9d7e214a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:26:29.278538Z", "start_time": "2023-08-12T12:26:29.265519Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "y = True\n", "print(y)" ] }, { "cell_type": "markdown", "id": "6ef1a41e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "变量命名规则:\n", "- **必须以字母或下划线(`_`)开头**\n", "- 命名可由字母、数字和下划线组成\n", "- **大小写敏感**\n", "- 尽量**避免使用保留字**命名" ] }, { "cell_type": "code", "execution_count": 12, "id": "455ea687", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:30:25.758511Z", "start_time": "2023-08-12T12:30:25.741457Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "numberOfRabbits = 40\n", "courseIs15112 = True" ] }, { "cell_type": "code", "execution_count": 13, "id": "1dd257e1", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:30:27.468546Z", "start_time": "2023-08-12T12:30:27.448622Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (1604835474.py, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m Cell \u001b[1;32mIn [13], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m 99problems = 0 # 会崩溃!因为变量名以数字开头\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "99problems = 0 # 会崩溃!因为变量名以数字开头" ] }, { "cell_type": "markdown", "id": "5bfbb648", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 保留字" ] }, { "cell_type": "code", "execution_count": 14, "id": "86b01766", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:30:29.195893Z", "start_time": "2023-08-12T12:30:29.174701Z" }, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "['False',\n", " 'None',\n", " 'True',\n", " '__peg_parser__',\n", " 'and',\n", " 'as',\n", " 'assert',\n", " 'async',\n", " 'await',\n", " 'break',\n", " 'class',\n", " 'continue',\n", " 'def',\n", " 'del',\n", " 'elif',\n", " 'else',\n", " 'except',\n", " 'finally',\n", " 'for',\n", " 'from',\n", " 'global',\n", " 'if',\n", " 'import',\n", " 'in',\n", " 'is',\n", " 'lambda',\n", " 'nonlocal',\n", " 'not',\n", " 'or',\n", " 'pass',\n", " 'raise',\n", " 'return',\n", " 'try',\n", " 'while',\n", " 'with',\n", " 'yield']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import keyword\n", "keyword.kwlist" ] }, { "cell_type": "markdown", "id": "5b2a4a68", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 更新变量" ] }, { "cell_type": "code", "execution_count": 15, "id": "f731b4e4", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:30:35.293640Z", "start_time": "2023-08-12T12:30:35.288602Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "x = 5\n", "x += 2 # 等价于 x = x + 2\n", "print(x) # 7" ] }, { "cell_type": "code", "execution_count": 16, "id": "7a27cf1d", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:30:38.296374Z", "start_time": "2023-08-12T12:30:38.284352Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "35\n" ] } ], "source": [ "# 换成其他运算符也是同理\n", "y = 350\n", "y //= 10\n", "print(y) # 35" ] }, { "cell_type": "markdown", "id": "5e5231c6", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 多变量赋值" ] }, { "cell_type": "code", "execution_count": 17, "id": "a50d96fe", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:34:11.986967Z", "start_time": "2023-08-12T12:34:11.973246Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a=2, b=2, c=2\n" ] } ], "source": [ "a = b = c = 2\n", "print(f\"a={a}, b={b}, c={c}\")" ] }, { "cell_type": "code", "execution_count": 18, "id": "7f38bbc0", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:34:23.383144Z", "start_time": "2023-08-12T12:34:23.373363Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a=1, b=2, c=6\n" ] } ], "source": [ "a, b, c = 1, 2, 6\n", "print(f\"a={a}, b={b}, c={c}\")" ] }, { "cell_type": "markdown", "id": "e4e14cb5", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 函数 Functions\n", "\n", "> A function is a procedure (a sequence of statements) stored under a name that can be used repeatedly by calling the name.\n", "\n", "- 函数是一个名字,代表一串代码序列(流程、过程)\n", "- 函数由两个部分组成:**header** 和 **body**\n", " - `header` 用于定义函数接口(函数 **名称** 与 **参数**)\n", " - `body` 包含函数所需要执行的操作" ] }, { "cell_type": "markdown", "id": "93c8a4be", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## header\n", "\n", "`header` 用于定义函数的**名称**和**参数**\n", "\n", "- 当函数被**调用**时,参数将会作为变量被提供给函数的 `body` 部分\n", "- 可以提供多个参数(用逗号 `,` 分隔),也可以不提供参数(0 个)\n", "- `header` 以冒号(`:`)结尾,代表后面会跟着 `body` 部分\n", "\n", "函数的 `header` 的写法:" ] }, { "cell_type": "code", "execution_count": 19, "id": "30bbf674", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:44:35.531373Z", "start_time": "2023-08-12T12:44:35.501507Z" } }, "outputs": [], "source": [ "def functionName(parameters):\n", " pass # 函数的 body 部分,这里使用 pass 代替" ] }, { "cell_type": "markdown", "id": "82652b0a", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## body\n", "\n", "`body` 包含函数执行的语句(`statement`)\n", "\n", "- 语句需要**缩进**(由 Code Style Guide 决定)\n", "- 当语句**不再缩进,函数部分结束**\n", "- 一般会使用 `return` 语句,来让函数返回其结果,但不是必须的\n", "\n", "> 类似于用一个 `=` 来对多个变量赋值,函数的返回结果也可以不止一个(用逗号 `,` 分隔)" ] }, { "cell_type": "markdown", "id": "3b4ff1a6", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "下面我们用一个例子来解释函数的细节" ] }, { "cell_type": "code", "execution_count": 21, "id": "005e7401", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:45:31.276515Z", "start_time": "2023-08-12T12:45:31.263935Z" } }, "outputs": [], "source": [ "def double(x):\n", " print(\"我在一个名叫 “double” 函数里!\")\n", " return 2 * x" ] }, { "cell_type": "markdown", "id": "bd4ccc98", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "- 我们使用**函数名**来调用函数\n", "- 函数名后紧跟**一对括号**\n", "- 括号中是我们设定的参数的**值**,一个不多,一个不少(这很重要)\n", "- 函数会**返回**设定的 `return` 语句的值\n", "\n", "> 调用示例函数 `double()` 会返回一个值(`2 * x`)" ] }, { "cell_type": "code", "execution_count": 23, "id": "61d0b8a0", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:45:42.899338Z", "start_time": "2023-08-12T12:45:42.886808Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "我在一个名叫 “double” 函数里!\n", "4\n" ] } ], "source": [ "print(double(2)) # 会输出 4" ] }, { "cell_type": "code", "execution_count": 25, "id": "fe3fcc9f", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:46:20.335526Z", "start_time": "2023-08-12T12:46:20.319819Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "我在一个名叫 “double” 函数里!\n", "10\n" ] } ], "source": [ "print(double(5)) # 会输出 10" ] }, { "cell_type": "code", "execution_count": 26, "id": "76e530c1", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:46:30.467380Z", "start_time": "2023-08-12T12:46:30.452758Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "我在一个名叫 “double” 函数里!\n", "5\n" ] } ], "source": [ "print(double(1) + 3) # 会输出 5" ] }, { "cell_type": "markdown", "id": "7e18a170", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "函数可以有任意多个参数,也可以一个都没有" ] }, { "cell_type": "code", "execution_count": 27, "id": "feda057f", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:46:40.828257Z", "start_time": "2023-08-12T12:46:40.815199Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "# 三个参数\n", "def f(x, y, z):\n", " return x + y + z\n", "\n", "print(f(1, 3, 2)) # 返回 6" ] }, { "cell_type": "code", "execution_count": 28, "id": "5b3ec990", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:46:59.660415Z", "start_time": "2023-08-12T12:46:59.639326Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n" ] } ], "source": [ "# 无参数\n", "def g():\n", " return 42\n", "\n", "print(g()) # 返回 42" ] }, { "cell_type": "markdown", "id": "28cf3e87", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "可是如果参数**数目没有匹配**的话……Oops!" ] }, { "cell_type": "code", "execution_count": 29, "id": "53f6e955", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:09.276277Z", "start_time": "2023-08-12T12:47:08.551650Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "TypeError", "evalue": "g() takes 0 positional arguments but 1 was given", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn [29], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mg\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m)\u001b[49m)\n", "\u001b[1;31mTypeError\u001b[0m: g() takes 0 positional arguments but 1 was given" ] } ], "source": [ "print(g(2)) # 崩溃!" ] }, { "cell_type": "code", "execution_count": 30, "id": "c19b7603", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:17.250728Z", "start_time": "2023-08-12T12:47:17.224050Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "TypeError", "evalue": "f() missing 1 required positional argument: 'z'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn [30], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mf\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m)\u001b[49m)\n", "\u001b[1;31mTypeError\u001b[0m: f() missing 1 required positional argument: 'z'" ] } ], "source": [ "print(f(1, 2)) # 也会崩溃" ] }, { "cell_type": "markdown", "id": "e8da06ea", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 多返回值" ] }, { "cell_type": "code", "execution_count": 31, "id": "6910224a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:26.396779Z", "start_time": "2023-08-12T12:47:26.381658Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def Multi_Return_Values():\n", " return 9, 2, 8" ] }, { "cell_type": "code", "execution_count": 32, "id": "1ad91cc5", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:27.985584Z", "start_time": "2023-08-12T12:47:27.967961Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a=9, b=2, c=8\n" ] } ], "source": [ "a, b, c = Multi_Return_Values()\n", "print(f\"a={a}, b={b}, c={c}\")" ] }, { "cell_type": "markdown", "id": "28486716", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 语句与表达式 Statements and Expressions" ] }, { "cell_type": "markdown", "id": "d151b9a8", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "> An expression is a data value or an operation that evaluates to a value.\n", "\n", "对于表达式\n", "- 它本身是**值**\n", "- 它的**计算结果是值**" ] }, { "cell_type": "markdown", "id": "d72477ee", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "> Statements, by contrast, do not evaluate to a value, and we can't print them. Usually they perform some action, though.\n", "\n", "对于语句\n", "- 它不是值\n", "- 它不能打印\n", "- 但它能**执行一些操作**" ] }, { "cell_type": "markdown", "id": "bdfbc819", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "表达式的一些例子" ] }, { "cell_type": "code", "execution_count": 33, "id": "62aa19ae", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:42.101736Z", "start_time": "2023-08-12T12:47:42.080465Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "4" ] }, { "cell_type": "code", "execution_count": 34, "id": "1dc1cad6", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:43.657970Z", "start_time": "2023-08-12T12:47:43.643405Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'Hello World'" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"Hello World\"" ] }, { "cell_type": "code", "execution_count": 35, "id": "2db65c3b", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:44.966446Z", "start_time": "2023-08-12T12:47:44.952852Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7 + 2" ] }, { "cell_type": "code", "execution_count": 36, "id": "1d854d2c", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:46.407892Z", "start_time": "2023-08-12T12:47:46.396211Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "True or False" ] }, { "cell_type": "code", "execution_count": 37, "id": "950da285", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:47.921853Z", "start_time": "2023-08-12T12:47:47.913310Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(2 < 3) and (9 > 0)" ] }, { "cell_type": "markdown", "id": "a3d987c0", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Python 只能 print 值和表达式,如果你能用 `print()` 输出它,那它就是表达式" ] }, { "cell_type": "code", "execution_count": 38, "id": "718d4ce6", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:52.264718Z", "start_time": "2023-08-12T12:47:52.246775Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print((2 < 3) and (9 > 0))" ] }, { "cell_type": "markdown", "id": "70f51fd9", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "语句的一些例子" ] }, { "cell_type": "code", "execution_count": 39, "id": "59ed7d68", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:55.208041Z", "start_time": "2023-08-12T12:47:55.199000Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def f(x):\n", " return 5*x" ] }, { "cell_type": "code", "execution_count": 40, "id": "5c963056", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:47:57.090665Z", "start_time": "2023-08-12T12:47:57.078499Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "x = 5 + 4" ] }, { "cell_type": "code", "execution_count": 42, "id": "cc3380e7", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:48:14.819663Z", "start_time": "2023-08-12T12:48:14.811075Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "if 10 > 5:\n", " y = 5 + 3" ] }, { "cell_type": "markdown", "id": "06873939", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 内置函数 Builtin Functions" ] }, { "cell_type": "markdown", "id": "31a03d25", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "就是 Python 自己带的函数啦🤗" ] }, { "cell_type": "markdown", "id": "6dbb9d07", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 类型转换" ] }, { "cell_type": "code", "execution_count": 43, "id": "6065476a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:49:28.688072Z", "start_time": "2023-08-12T12:49:28.667738Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "print(bool(0)) # 转换为布尔类型(True or False)" ] }, { "cell_type": "code", "execution_count": 44, "id": "6cdb3bed", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:49:50.183255Z", "start_time": "2023-08-12T12:49:50.165610Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42.0\n" ] } ], "source": [ "print(float(42)) # 转换为浮点数" ] }, { "cell_type": "code", "execution_count": 45, "id": "d72f4e0f", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:50:14.256834Z", "start_time": "2023-08-12T12:50:14.239768Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "print(int(2.8)) # 转换为一个整数(舍弃小数点)" ] }, { "cell_type": "markdown", "id": "533940d3", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 一些基本数学函数\n", "但是它们不在 `math` 库中" ] }, { "cell_type": "code", "execution_count": 46, "id": "dae12973", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:50:22.364372Z", "start_time": "2023-08-12T12:50:22.348349Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "print(abs(-5)) # 绝对值" ] }, { "cell_type": "code", "execution_count": 47, "id": "0a9a57a4", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:50:32.682408Z", "start_time": "2023-08-12T12:50:32.664262Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "print(max(2,3)) # 返回最大值" ] }, { "cell_type": "code", "execution_count": 48, "id": "144c8585", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:50:40.060884Z", "start_time": "2023-08-12T12:50:40.041638Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "print(min(2,3)) # 返回最小值" ] }, { "cell_type": "code", "execution_count": 49, "id": "68df2a1a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:51:33.055856Z", "start_time": "2023-08-12T12:51:33.049816Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1024\n" ] } ], "source": [ "print(pow(2,10)) # 次方运算,等价于 2**10" ] }, { "cell_type": "code", "execution_count": 50, "id": "6a7bb062", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T12:52:24.164161Z", "start_time": "2023-08-12T12:52:24.142042Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.35\n" ] } ], "source": [ "print(round(2.354, 2)) # 取最近的一个整数(并不完全是四舍五入,二进制精度丢失)" ] }, { "cell_type": "markdown", "id": "76250104", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 变量作用域 Variable Scope\n", "- 每个变量都有属于自己的作用范围\n", "- 超出作用范围后,变量不可见" ] }, { "cell_type": "markdown", "id": "379c51e9", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "我们设定一个函数 `f(x)`, 它的内部有 `x` 和 `y` 两个变量\n", "\n", "> 记得一定要重启 Jupyter Kernel!" ] }, { "cell_type": "code", "execution_count": 5, "id": "380c348c", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:02:03.373827Z", "start_time": "2023-08-12T13:02:03.357640Z" } }, "outputs": [], "source": [ "def f(x):\n", " print(\"x:\", x)\n", " y = 5\n", " print(\"y:\", y)\n", " return x + y" ] }, { "cell_type": "code", "execution_count": 2, "id": "ba9e76fc", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:00:27.877293Z", "start_time": "2023-08-12T13:00:27.861846Z" }, "run_control": { "marked": false }, "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x: 4\n", "y: 5\n", "9\n" ] } ], "source": [ "print(f(4))" ] }, { "cell_type": "code", "execution_count": 3, "id": "b8157e63", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:00:31.314737Z", "start_time": "2023-08-12T13:00:31.282789Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn [3], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mx\u001b[49m)\n", "\u001b[1;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "source": [ "print(x) # crash!" ] }, { "cell_type": "code", "execution_count": 4, "id": "ddcc02e5", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:00:33.400337Z", "start_time": "2023-08-12T13:00:33.378191Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'y' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn [4], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43my\u001b[49m)\n", "\u001b[1;31mNameError\u001b[0m: name 'y' is not defined" ] } ], "source": [ "print(y) # crash!" ] }, { "cell_type": "markdown", "id": "649135bb", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "函数内的变量具有**局部作用域**,它只存在于函数内部,与其他函数中的同名变量无关" ] }, { "cell_type": "code", "execution_count": 10, "id": "e823d1e0", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:03:57.978021Z", "start_time": "2023-08-12T13:03:57.967044Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "In f, x = 4\n", "In g, x = 2\n", "In f, x = 6\n", "In g, x = 2\n", "20\n" ] } ], "source": [ "def f(x):\n", " print(\"In f, x =\", x)\n", " x += 5\n", " return x\n", "\n", "def g(x):\n", " y = f(x*2)\n", " print(\"In g, x =\", x)\n", " z = f(x*3)\n", " print(\"In g, x =\", x)\n", " return y + z\n", "\n", "print(g(2))" ] }, { "cell_type": "code", "execution_count": 1, "id": "f2f847ac", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:04:02.813410Z", "start_time": "2023-08-12T13:04:02.790320Z" }, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=def%20f%28x%29%3A%0A%20%20%20%20print%28%22In%20f,%20x%20%3D%22,%20x%29%0A%20%20%20%20x%20%2B%3D%205%0A%20%20%20%20return%20x%0A%0Adef%20g%28x%29%3A%0A%20%20%20%20y%20%3D%20f%28x*2%29%0A%20%20%20%20print%28%22In%20g,%20x%20%3D%22,%20x%29%0A%20%20%20%20z%20%3D%20f%28x*3%29%0A%20%20%20%20print%28%22In%20g,%20x%20%3D%22,%20x%29%0A%20%20%20%20return%20y%20%2B%20z%0A%0Aprint%28g%282%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "code", "execution_count": 12, "id": "fb2273a8", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:04:38.169294Z", "start_time": "2023-08-12T13:04:38.150851Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "In f, x = 1\n", "In f, x = 10\n", "In f, x = 60\n", "50\n" ] } ], "source": [ "def f(x):\n", " print(\"In f, x =\", x)\n", " x += 7\n", " return round(x / 3)\n", "\n", "def g(x):\n", " x *= 10\n", " return 2 * f(x)\n", "\n", "def h(x):\n", " x += 3\n", " return f(x+4) + g(x)\n", "\n", "print(h(f(1)))" ] }, { "cell_type": "code", "execution_count": 13, "id": "d7947799", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:04:40.450897Z", "start_time": "2023-08-12T13:04:40.416179Z" }, "run_control": { "marked": false }, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=def%20f%28x%29%3A%0A%20%20%20%20print%28%22In%20f,%20x%20%3D%22,%20x%29%0A%20%20%20%20x%20%2B%3D%207%0A%20%20%20%20return%20round%28x%20/%203%29%0A%0Adef%20g%28x%29%3A%0A%20%20%20%20x%20*%3D%2010%0A%20%20%20%20return%202%20*%20f%28x%29%0A%0Adef%20h%28x%29%3A%0A%20%20%20%20x%20%2B%3D%203%0A%20%20%20%20return%20f%28x%2B4%29%20%2B%20g%28x%29%0A%0Aprint%28h%28f%281%29%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "markdown", "id": "8fe6bf91", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "在函数外部定义变量时,变量具有全局作用域,在任何地方都可以使用\n", "\n", "我们应该**尽量避免使用全局变量**,但是在非常少的一些场合你会需要用到它" ] }, { "cell_type": "code", "execution_count": 14, "id": "aa728846", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:05:34.257193Z", "start_time": "2023-08-12T13:05:34.240115Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "105\n", "106\n", "100\n" ] } ], "source": [ "g = 100\n", "\n", "def f(x):\n", " return x + g\n", "\n", "print(f(5)) # 105\n", "print(f(6)) # 106\n", "print(g) # 100" ] }, { "cell_type": "code", "execution_count": 15, "id": "7a01a437", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:05:49.249347Z", "start_time": "2023-08-12T13:05:49.227296Z" }, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=g%20%3D%20100%0A%0Adef%20f%28x%29%3A%0A%20%20%20%20return%20x%20%2B%20g%0A%0Aprint%28f%285%29%29%20%23%20105%0Aprint%28f%286%29%29%20%23%20106%0Aprint%28g%29%20%20%20%20%23%20100&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "code", "execution_count": 23, "id": "af4ed175", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:20:55.270958Z", "start_time": "2023-08-12T13:20:55.256344Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "106\n", "108\n", "102\n" ] } ], "source": [ "g = 100\n", "\n", "def f(x):\n", " # 如果我们想要修改 g 的值,我们必须声明它是全局变量\n", " # 否则 Python 会假设它是局部变量\n", " global g\n", " g += 1\n", " return x + g\n", "\n", "print(f(5)) # 106\n", "print(f(6)) # 108\n", "print(g) # 102" ] }, { "cell_type": "code", "execution_count": 1, "id": "bb386ea0", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T14:00:54.780214Z", "start_time": "2023-08-12T14:00:54.758214Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=g%20%3D%20100%0A%0Adef%20f%28x%29%3A%0A%20%20%20%20global%20g%0A%20%20%20%20g%20%2B%3D%201%0A%20%20%20%20return%20x%20%2B%20g%0A%0Aprint%28f%285%29%29%20%23%20106%0Aprint%28f%286%29%29%20%23%20108%0Aprint%28g%29%20%20%20%20%23%20102&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "markdown", "id": "8c59c047", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 返回语句 Return Statements" ] }, { "cell_type": "code", "execution_count": 24, "id": "919a8d8b", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:21:02.545173Z", "start_time": "2023-08-12T13:21:02.538506Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def isPositive(x):\n", " return (x > 0)" ] }, { "cell_type": "code", "execution_count": 25, "id": "8ed7b9be", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:21:04.260509Z", "start_time": "2023-08-12T13:21:04.241887Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print(isPositive(5)) # True" ] }, { "cell_type": "code", "execution_count": 26, "id": "5a9a07bc", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:21:05.688493Z", "start_time": "2023-08-12T13:21:05.680764Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "print(isPositive(-5)) # False" ] }, { "cell_type": "code", "execution_count": 27, "id": "f18b69e3", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:21:10.004034Z", "start_time": "2023-08-12T13:21:09.996999Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "print(isPositive(0)) # False" ] }, { "cell_type": "markdown", "id": "78a01452", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "一旦返回,函数**立即结束!**" ] }, { "cell_type": "code", "execution_count": 28, "id": "d6ac5524", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:21:11.880574Z", "start_time": "2023-08-12T13:21:11.862874Z" }, "run_control": { "marked": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello!\n", "True\n" ] } ], "source": [ "def isPositive(x):\n", " print(\"Hello!\") # 会运行\n", " return (x > 0)\n", " print(\"Goodbye!\") # 不会运行\n", "\n", "print(isPositive(5)) # 输出 “Hello!” 然后返回 True" ] }, { "cell_type": "code", "execution_count": 2, "id": "b5fd4d1a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T14:00:54.796214Z", "start_time": "2023-08-12T14:00:54.784213Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=def%20isPositive%28x%29%3A%0A%20%20%20%20print%28%22Hello!%22%29%0A%20%20%20%20return%20%28x%20%3E%200%29%0A%20%20%20%20print%28%22Goodbye!%22%29%0A%0Aprint%28isPositive%285%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "markdown", "id": "d5d8fdc1", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "没有返回语句的时候,函数会返回 `None`" ] }, { "cell_type": "code", "execution_count": 30, "id": "01638b54", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:23:32.878876Z", "start_time": "2023-08-12T13:23:32.870826Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "def f(x):\n", " x + 42\n", "\n", "print(f(5)) # None" ] }, { "cell_type": "code", "execution_count": 31, "id": "2fc25047", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:23:35.808886Z", "start_time": "2023-08-12T13:23:35.794871Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "def f(x):\n", " result = x + 42\n", "\n", "print(f(5)) # None" ] }, { "cell_type": "markdown", "id": "5c91f461", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Print versus Return\n", "\n", "`print()` 和 `return` 是初学者比较容易出现的错误" ] }, { "cell_type": "code", "execution_count": 37, "id": "d098a42a", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:24:46.728266Z", "start_time": "2023-08-12T13:24:46.714666Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def cubed(x):\n", " print(x**3) # 这里的操作不太合适" ] }, { "cell_type": "code", "execution_count": 36, "id": "81b1c6f2", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:24:36.103416Z", "start_time": "2023-08-12T13:24:36.084254Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "cubed(2) # 但是似乎看起来也正常运行了" ] }, { "cell_type": "code", "execution_count": 39, "id": "ac30b2f1", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:27:06.479048Z", "start_time": "2023-08-12T13:27:06.459089Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27\n", "None\n" ] } ], "source": [ "print(cubed(3)) # 应该也能有效(但是返回 None,太怪了)" ] }, { "cell_type": "code", "execution_count": 41, "id": "7b91b102", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:27:36.453144Z", "start_time": "2023-08-12T13:27:36.400998Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "64\n" ] }, { "ename": "TypeError", "evalue": "unsupported operand type(s) for *: 'int' and 'NoneType'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn [41], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;241;43m2\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mcubed\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m4\u001b[39;49m\u001b[43m)\u001b[49m)\n", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for *: 'int' and 'NoneType'" ] } ], "source": [ "print(2*cubed(4)) # Error!" ] }, { "cell_type": "markdown", "id": "062fbe98", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "正确写法:" ] }, { "cell_type": "code", "execution_count": 42, "id": "833a1656", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:27:49.406524Z", "start_time": "2023-08-12T13:27:49.392209Z" } }, "outputs": [], "source": [ "def cubed(x):\n", " return (x**3) # 这样做更好" ] }, { "cell_type": "code", "execution_count": 44, "id": "f39ef158", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:28:17.713367Z", "start_time": "2023-08-12T13:28:17.696883Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cubed(2) #似乎输出被忽略了,为什么?" ] }, { "cell_type": "code", "execution_count": 45, "id": "7be0a635", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:28:32.182161Z", "start_time": "2023-08-12T13:28:32.170529Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27\n" ] } ], "source": [ "print(cubed(3)) # 有效了!" ] }, { "cell_type": "code", "execution_count": 46, "id": "6f242cac", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:28:48.014221Z", "start_time": "2023-08-12T13:28:48.001420Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "128\n" ] } ], "source": [ "print(2*cubed(4)) # 也是有效的!" ] }, { "cell_type": "markdown", "id": "23385d7f", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 函数组合 Function Composition\n", "\n", "对于嵌套的函数而言,应该最先运行最内层的函数" ] }, { "cell_type": "code", "execution_count": 48, "id": "d5c18e93", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:31:00.319598Z", "start_time": "2023-08-12T13:31:00.299813Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "500\n" ] } ], "source": [ "def f(w):\n", " return 10*w\n", "\n", "def g(x, y):\n", " return f(3*x) + y #在我们返回它之前,我们必须先执行 f(3*x)\n", "\n", "def h(z):\n", " return f(g(z, f(z+1))) # 最内部的 f(z+1) 必须先执行\n", "\n", "print(h(1)) # 你一定得“亲眼看看”" ] }, { "cell_type": "code", "execution_count": 3, "id": "96a5b48c", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T14:00:54.812211Z", "start_time": "2023-08-12T14:00:54.799214Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=def%20f%28w%29%3A%0A%20%20%20%20return%2010*w%0A%0Adef%20g%28x,%20y%29%3A%0A%20%20%20%20return%20f%283*x%29%20%2B%20y%0A%0Adef%20h%28z%29%3A%0A%20%20%20%20return%20f%28g%28z,%20f%28z%2B1%29%29%29%0A%0Aprint%28h%281%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "markdown", "id": "7dbb9282", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Helper Functions\n", "\n", "编写函数是用来解决问题的\n", "\n", "我们还可以编写函数来存储那些经常被用到的一系列操作\n", "\n", "这种函数就叫做 `Helper Function`" ] }, { "cell_type": "code", "execution_count": 49, "id": "006e0632", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T13:31:42.242315Z", "start_time": "2023-08-12T13:31:42.220575Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "4\n" ] } ], "source": [ "def onesDigit(n):\n", " return n%10\n", "\n", "def largerOnesDigit(x, y):\n", " return max(onesDigit(x), onesDigit(y))\n", "\n", "print(largerOnesDigit(134, 672)) # 4\n", "print(largerOnesDigit(132, 674)) # 依然是 4" ] }, { "cell_type": "code", "execution_count": 4, "id": "217663c6", "metadata": { "ExecuteTime": { "end_time": "2023-08-12T14:00:54.827770Z", "start_time": "2023-08-12T14:00:54.815772Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/render.html#code=def%20onesDigit%28n%29%3A%0A%20%20%20%20return%20n%2510%0A%0Adef%20largerOnesDigit%28x,%20y%29%3A%0A%20%20%20%20return%20max%28onesDigit%28x%29,%20onesDigit%28y%29%29%0A%0Aprint%28largerOnesDigit%28134,%20672%29%29%0Aprint%28largerOnesDigit%28132,%20674%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=600)" ] }, { "cell_type": "markdown", "id": "00e340d3", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "> **Don’t be the person who “never quite understood” something like recursion.**\n", ">\n", "> —— Teach Yourself Computer Science\n", "\n", "补充资料:\n", "- [递归&分治](https://oi-wiki.org/basic/divide-and-conquer/)\n", "- [Teach Yourself Computer Science](https://teachyourselfcs.com/)" ] }, { "cell_type": "markdown", "id": "ad58e756", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 总结\n", "\n", "- 变量只是个标签,物理设备上有啥才是重点\n", "- 函数定义:`def`、header、body、缩进、`return`\n", "- 函数是有作用域的,类似双层玻璃,里面可以看见外面,外面不能看见里面\n", "- Helper Function 有时候会很有用\n", "- **一定要亲眼看你的代码是怎么跑起来的**" ] }, { "cell_type": "markdown", "id": "70d64bfb", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Thank You ;-)\n", "Datawhale 聪明办法学 Python 教学团队出品\n", "\n", "## 关注我们\n", "Datawhale 是一个专注 AI 领域的开源组织,以“for the learner,和学习者一起成长”为愿景,构建对学习者最有价值的开源学习社区。关注我们,一起学习成长。\n", "
" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" }, "rise": { "overlay": "
" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false }, "vscode": { "interpreter": { "hash": "2604979e475c72c3999e63049dbb75eb38f7d29b6d0ace0384f7e020f0ee1ffa" } } }, "nbformat": 4, "nbformat_minor": 5 }