{ "cells": [ { "cell_type": "markdown", "id": "b01ef668", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 聪明办法学 Python 2nd Edition\n", "## Chapter 4 条件 Conditionals\n", "---\n", "聪明办法学 Python 教学团队\n", "\n", "

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

" ] }, { "cell_type": "markdown", "id": "dc9d6a25", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "" ] }, { "cell_type": "markdown", "id": "0032e83a", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# if 语句 if statement" ] }, { "cell_type": "markdown", "id": "238372c3", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "# Conditionals Make Decisions" ] }, { "cell_type": "markdown", "id": "f75e3df4", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## if 语句流程\n", "\n", "\n", "\n", "
" ] }, { "cell_type": "markdown", "id": "31a5bc11", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 一个例子" ] }, { "cell_type": "code", "execution_count": 1, "id": "01dafc2e", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.015079Z", "start_time": "2023-08-21T06:02:58.005648Z" }, "init_cell": true, "slideshow": { "slide_type": "" } }, "outputs": [], "source": [ "def f(x):\n", " print(\"A\", end=\"\")\n", " if x == 0:\n", " print(\"B\", end=\"\")\n", " print(\"C\", end=\"\")\n", " print(\"D\")" ] }, { "cell_type": "code", "execution_count": 77, "id": "ba9a282d", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:53:54.071452Z", "start_time": "2023-08-21T04:53:54.063387Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AD\n" ] } ], "source": [ "f(1)" ] }, { "cell_type": "markdown", "id": "11e4a683", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 一个更有意思的例子:\n", "\n", "任务:实现一个函数,返回输入数字的绝对值\n", "\n", "> Python 内置了一个函数叫 `abs()` 用于绝对值计算,所以我们将函数命名成 `abs1`、`abs2`……" ] }, { "cell_type": "code", "execution_count": 2, "id": "56ef94b3", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.030159Z", "start_time": "2023-08-21T06:02:58.017860Z" }, "init_cell": true, "run_control": { "marked": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "def abs1(n):\n", " if n < 0:\n", " n = -n\n", " return n" ] }, { "cell_type": "markdown", "id": "eff17694", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "写在一行" ] }, { "cell_type": "code", "execution_count": 3, "id": "60f99adf", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.045232Z", "start_time": "2023-08-21T06:02:58.031948Z" }, "init_cell": true, "run_control": { "marked": false } }, "outputs": [], "source": [ "def abs2(n):\n", " if n < 0: n = -n \n", " return n" ] }, { "cell_type": "markdown", "id": "8083b429", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "除非有特殊原因,否则**强烈建议不要这样写**" ] }, { "cell_type": "markdown", "id": "25bcd1bf", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "多个返回语句 " ] }, { "cell_type": "code", "execution_count": 4, "id": "9f27ce07", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.061044Z", "start_time": "2023-08-21T06:02:58.047229Z" }, "init_cell": true, "run_control": { "marked": false } }, "outputs": [], "source": [ "def abs3(n):\n", " if n < 0:\n", " return -n\n", " return n" ] }, { "cell_type": "markdown", "id": "0164f5c5", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "使用布尔表达式" ] }, { "cell_type": "code", "execution_count": 5, "id": "fdba9796", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.076762Z", "start_time": "2023-08-21T06:02:58.062962Z" }, "init_cell": true }, "outputs": [], "source": [ "def abs4(n):\n", " return (n < 0)*(-n) + (n>=0)*(n) # 这家伙长得太奇怪了" ] }, { "cell_type": "markdown", "id": "98c02aa7", "metadata": {}, "source": [ "**不要这样写!**" ] }, { "cell_type": "markdown", "id": "ef8717e6", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "验证结果正确性" ] }, { "cell_type": "code", "execution_count": 82, "id": "12f5e6f2", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:54:05.910500Z", "start_time": "2023-08-21T04:54:05.894373Z" }, "run_control": { "marked": false }, "slideshow": { "slide_type": "" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "abs1(5) = 5 and abs1(-5) = 5\n", "abs2(5) = 5 and abs2(-5) = 5\n", "abs3(5) = 5 and abs3(-5) = 5\n", "abs4(5) = 5 and abs4(-5) = 5\n" ] } ], "source": [ "print(\"abs1(5) =\", abs1(5), \"and abs1(-5) =\", abs1(-5))\n", "print(\"abs2(5) =\", abs2(5), \"and abs2(-5) =\", abs2(-5))\n", "print(\"abs3(5) =\", abs3(5), \"and abs3(-5) =\", abs3(-5))\n", "print(\"abs4(5) =\", abs4(5), \"and abs4(-5) =\", abs4(-5))" ] }, { "cell_type": "markdown", "id": "dc48dbf9", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# if-else 语句 if-else statement" ] }, { "cell_type": "code", "execution_count": 93, "id": "dace628a", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:58:05.830321Z", "start_time": "2023-08-21T04:58:04.195043Z" }, "cell_style": "split", "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x=9\n", "hello\n", "wahoo!\n", "goodbye\n" ] } ], "source": [ "x = input(\"x=\")\n", "x = float(x)\n", "print(\"hello\")\n", "if x < 10:\n", " print(\"wahoo!\")\n", "print(\"goodbye\")" ] }, { "cell_type": "markdown", "id": "ba89d17e", "metadata": { "cell_style": "split", "slideshow": { "slide_type": "-" } }, "source": [ "" ] }, { "cell_type": "code", "execution_count": 6, "id": "ad3fe352", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.091719Z", "start_time": "2023-08-21T06:02:58.078763Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "def f(x):\n", " print(\"A\", end=\"\")\n", " if x == 0: \n", " print(\"B\", end=\"\")\n", " print(\"C\", end=\"\")\n", " else:\n", " print(\"D\", end=\"\")\n", " if x == 1:\n", " print(\"E\", end=\"\")\n", " else:\n", " print(\"F\", end=\"\")\n", " print(\"G\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "dfdc919d", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.107769Z", "start_time": "2023-08-21T06:02:58.092721Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/visualize.html#code=def%20f%28x%29%3A%0A%20%20%20%20print%28%22A%22,%20end%3D%22%22%29%0A%20%20%20%20if%20x%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20print%28%22B%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20print%28%22C%22,%20end%3D%22%22%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print%28%22D%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20if%20x%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28%22E%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28%22F%22,%20end%3D%22%22%29%0A%20%20%20%20print%28%22G%22%29%0A%0Af%280%29%0Af%281%29%0Af%282%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=800)" ] }, { "cell_type": "markdown", "id": "6118eb49", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 重新设计 `abs()`" ] }, { "cell_type": "code", "execution_count": 8, "id": "1c7d2fda", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.123761Z", "start_time": "2023-08-21T06:02:58.109770Z" }, "cell_style": "split", "init_cell": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def abs5(n):\n", " if n >= 0:\n", " return n\n", " else:\n", " return -n" ] }, { "cell_type": "code", "execution_count": 9, "id": "d93d3e33", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.140063Z", "start_time": "2023-08-21T06:02:58.125764Z" }, "cell_style": "split", "init_cell": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def abs6(n):\n", " if n >= 0:\n", " sign = +1\n", " else:\n", " sign = -1\n", " return sign * n" ] }, { "cell_type": "code", "execution_count": 86, "id": "54f1e68d", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:54:35.479481Z", "start_time": "2023-08-21T04:54:35.471475Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "abs5(5) = 5 and abs5(-5) = 5\n", "abs6(5) = 5 and abs6(-5) = 5\n" ] } ], "source": [ "print(\"abs5(5) =\", abs5(5), \"and abs5(-5) =\", abs5(-5))\n", "print(\"abs6(5) =\", abs6(5), \"and abs6(-5) =\", abs6(-5))" ] }, { "cell_type": "markdown", "id": "42a169d6", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# if-elif-else 语句" ] }, { "cell_type": "markdown", "id": "fbf80422", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "" ] }, { "cell_type": "code", "execution_count": 10, "id": "2998e87b", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.155606Z", "start_time": "2023-08-21T06:02:58.142579Z" }, "init_cell": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "def f(x):\n", " print(\"A\", end=\"\")\n", " if x == 0:\n", " print(\"B\", end=\"\")\n", " print(\"C\", end=\"\")\n", " elif x == 1:\n", " print(\"D\", end=\"\")\n", " else:\n", " print(\"E\", end=\"\")\n", " if x == 2:\n", " print(\"F\", end=\"\")\n", " else:\n", " print(\"G\", end=\"\")\n", " print(\"H\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "5138e7ab", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.170639Z", "start_time": "2023-08-21T06:02:58.157609Z" }, "init_cell": true, "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame('https://pythontutor.com/visualize.html#code=def%20f%28x%29%3A%0A%20%20%20%20print%28%22A%22,%20end%3D%22%22%29%0A%20%20%20%20if%20x%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20print%28%22B%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20print%28%22C%22,%20end%3D%22%22%29%0A%20%20%20%20elif%20x%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20print%28%22D%22,%20end%3D%22%22%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print%28%22E%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20if%20x%20%3D%3D%202%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28%22F%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28%22G%22,%20end%3D%22%22%29%0A%20%20%20%20print%28%22H%22%29%0A%0Af%280%29%0Af%281%29%0Af%282%29%0Af%283%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=800)" ] }, { "cell_type": "markdown", "id": "97b472ea", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 另一个更有意思的例子:\n", "\n", "任务:实现一个函数,输入一元二次函数的各项系数,返回其解的个数。\n", "\n", "> 提示:一元二次方程 $ax^2+bx+c=0\\ (a \\neq 0)$ 的根与根的判别式 有如下关系:\n", ">\n", "> $$\\Delta = b^2 - 4 ac$$\n", "> - 当 $\\Delta > 0$ 时,方程有两个不相等的实数根;\n", "> - 当 $\\Delta = 0$ 时,方程有两个相等的实数根;\n", "> - 当 $\\Delta < 0$ 时,方程无实数根。" ] }, { "cell_type": "code", "execution_count": 99, "id": "5881d7d2", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T05:02:39.581449Z", "start_time": "2023-08-21T05:02:39.567894Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "y = 4*x**2 + 5*x + 1 has 2 root(s).\n", "y = 4*x**2 + 4*x + 1 has 1 root(s).\n", "y = 4*x**2 + 3*x + 1 has 0 root(s).\n" ] } ], "source": [ "def numberOfRoots(a, b, c):\n", " # 返回 y 的实数根(零点)数量: y = a*x**2 + b*x + c\n", " d = b**2 - 4*a*c\n", " if d > 0:\n", " return 2\n", " elif d == 0:\n", " return 1\n", " else:\n", " return 0\n", "\n", "print(\"y = 4*x**2 + 5*x + 1 has\", numberOfRoots(4,5,1), \"root(s).\")\n", "print(\"y = 4*x**2 + 4*x + 1 has\", numberOfRoots(4,4,1), \"root(s).\")\n", "print(\"y = 4*x**2 + 3*x + 1 has\", numberOfRoots(4,3,1), \"root(s).\")" ] }, { "cell_type": "markdown", "id": "f33da16e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## 再来一个例子:\n", "实现传说中的“学生分数登记管理系统”" ] }, { "cell_type": "code", "execution_count": 88, "id": "5d14a0ac", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:55:16.208398Z", "start_time": "2023-08-21T04:55:16.199291Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "103 --> A\n", " 88 --> B\n", " 70 --> C\n", " 61 --> D\n", " 22 --> F\n" ] } ], "source": [ "def getGrade(score):\n", " if score >= 90:\n", " grade = \"A\"\n", " elif score >= 80:\n", " grade = \"B\"\n", " elif score >= 70:\n", " grade = \"C\"\n", " elif score >= 60:\n", " grade = \"D\"\n", " else:\n", " grade = \"F\"\n", " return grade\n", "\n", "print(\"103 -->\", getGrade(103))\n", "print(\" 88 -->\", getGrade(88))\n", "print(\" 70 -->\", getGrade(70))\n", "print(\" 61 -->\", getGrade(61))\n", "print(\" 22 -->\", getGrade(22))" ] }, { "cell_type": "markdown", "id": "41686997", "metadata": { "ExecuteTime": { "end_time": "2022-12-29T17:21:03.594287Z", "start_time": "2022-12-29T17:21:03.577575Z" }, "slideshow": { "slide_type": "slide" } }, "source": [ "# if-else 推导式 if-else expression" ] }, { "cell_type": "code", "execution_count": 12, "id": "e6584f50", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T06:02:58.186259Z", "start_time": "2023-08-21T06:02:58.172559Z" }, "init_cell": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "def abs7(n):\n", " return n if (n >= 0) else -n" ] }, { "cell_type": "code", "execution_count": 90, "id": "95f2d010", "metadata": { "ExecuteTime": { "end_time": "2023-08-21T04:55:19.949341Z", "start_time": "2023-08-21T04:55:19.942482Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "abs7(5) = 5 and abs7(-5) = 5\n" ] } ], "source": [ "print(\"abs7(5) =\", abs7(5), \"and abs7(-5) =\", abs7(-5))" ] }, { "cell_type": "markdown", "id": "196e2b37", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# match-case 语句\n", "\n", "[菜鸟教程示例](https://www.runoob.com/python3/python3-conditional-statements.html#:~:text=2%20%E5%92%8C%203-,match...case,-Python%203.10%20%E5%A2%9E%E5%8A%A0)\n", "\n", "[HTTP 响应状态码](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status)" ] }, { "cell_type": "markdown", "id": "79d930ad", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T07:54:42.837616Z", "start_time": "2023-02-11T07:54:42.833617Z" }, "slideshow": { "slide_type": "slide" } }, "source": [ "# 随堂练习\n", "背景:小 $\\epsilon$ 是一名大四学生,他的学校毕业要求是通过大学英语六级考试,你能写个程序看看他能不能毕业嘛?\n", "\n", "输入格式:1-2 个整数,以空格分隔,第一个数字代表 CET 4 成绩,第二个数字代表 CET 6 成绩,如果四级未通过则没有六级成绩。\n", "\n", "输出格式:1 个字符串,`Yes` 代表能够毕业,`No` 代表不能毕业。\n", "\n", "输入示例:\n", "> 500 430\n", "\n", "输出示例:\n", "> Yes" ] }, { "cell_type": "markdown", "id": "8b6b14b1", "metadata": { "ExecuteTime": { "end_time": "2022-12-29T17:21:27.299272Z", "start_time": "2022-12-29T17:21:27.288661Z" }, "slideshow": { "slide_type": "slide" } }, "source": [ "# 清晰的代码风格 Clarity and style\n" ] }, { "cell_type": "markdown", "id": "4575317b", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**请注意:** 本节讨论的内容主要针对样式而非正确性,这里的所有例子都“正确的”,但有些例子比其他例子更巧妙,我们希望大家形成一个好的代码习惯。" ] }, { "cell_type": "markdown", "id": "f1c8a42d", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "否定条件(带有 `else` 部分)" ] }, { "cell_type": "code", "execution_count": 34, "id": "19eca0d7", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.212025Z", "start_time": "2023-02-11T08:41:12.193027Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "yes\n" ] } ], "source": [ "# 可能不清晰的:\n", "b = True\n", "if not b:\n", " print('no')\n", "else:\n", " print('yes')" ] }, { "cell_type": "code", "execution_count": 35, "id": "7b949c41", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.228024Z", "start_time": "2023-02-11T08:41:12.214027Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "yes\n" ] } ], "source": [ "# 清晰的:\n", "b = True\n", "if b:\n", " print('yes')\n", "else:\n", " print('no')" ] }, { "cell_type": "markdown", "id": "8134c681", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "空白的 `if` 部分" ] }, { "cell_type": "code", "execution_count": 36, "id": "82495396", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.244026Z", "start_time": "2023-02-11T08:41:12.229025Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "no\n" ] } ], "source": [ "# 不清晰的:\n", "b = False\n", "if b:\n", " pass\n", "else:\n", " print('no')" ] }, { "cell_type": "code", "execution_count": 37, "id": "5704094b", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.259023Z", "start_time": "2023-02-11T08:41:12.246026Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "no\n" ] } ], "source": [ "# 清晰的:\n", "b = False\n", "if not b:\n", " print('no')\n" ] }, { "cell_type": "markdown", "id": "2db0414f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "用嵌套的 `if` 而不是 `and` 来判断" ] }, { "cell_type": "code", "execution_count": 38, "id": "db798f43", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.275024Z", "start_time": "2023-02-11T08:41:12.261025Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "both!\n" ] } ], "source": [ "# 混乱的:\n", "b1 = True\n", "b2 = True\n", "if b1:\n", " if b2:\n", " print('both!')" ] }, { "cell_type": "code", "execution_count": 39, "id": "0e19fe6e", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.291024Z", "start_time": "2023-02-11T08:41:12.277029Z" }, "cell_style": "split", "run_control": { "marked": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "both!\n" ] } ], "source": [ "# 清晰的:\n", "b1 = True\n", "b2 = True\n", "if b1 and b2:\n", " print('both!')" ] }, { "cell_type": "markdown", "id": "033655b5", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "使用 `if` 而不是 `else` 来控制" ] }, { "cell_type": "code", "execution_count": 40, "id": "d58e59e1", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.307024Z", "start_time": "2023-02-11T08:41:12.293029Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "yes\n" ] } ], "source": [ "# 可能会引入 bug:\n", "b = True\n", "if b:\n", " print('yes')\n", "if not b:\n", " print('no')" ] }, { "cell_type": "code", "execution_count": 41, "id": "7414bacc", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.323025Z", "start_time": "2023-02-11T08:41:12.309028Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "yes\n" ] } ], "source": [ "# 更好的做法:\n", "b = True\n", "if b:\n", " print('yes')\n", "else:\n", " print('no')" ] }, { "cell_type": "markdown", "id": "3ca5c318", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "另外一个例子" ] }, { "cell_type": "code", "execution_count": 42, "id": "d1d64880", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.339024Z", "start_time": "2023-02-11T08:41:12.325028Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "large\n" ] } ], "source": [ "# 又混乱又有产生 bug 的风险:\n", "x = 10\n", "if x < 5:\n", " print('small')\n", "if (x >= 5) and (x < 10):\n", " print('medium')\n", "if (x >= 10) and (x < 15):\n", " print('large')\n", "if x >= 15:\n", " print('extra large')" ] }, { "cell_type": "code", "execution_count": 43, "id": "f02e863c", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.355024Z", "start_time": "2023-02-11T08:41:12.342025Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "large\n" ] } ], "source": [ "# 更好的做法:\n", "x = 10\n", "if x < 5:\n", " print('small')\n", "elif x < 10:\n", " print('medium')\n", "elif x < 15:\n", " print('large')\n", "else:\n", " print('extra large')" ] }, { "cell_type": "markdown", "id": "711b194c", "metadata": { "cell_style": "center", "slideshow": { "slide_type": "subslide" } }, "source": [ "再来一个例子" ] }, { "cell_type": "code", "execution_count": 47, "id": "d95f8fc4", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:58:19.602388Z", "start_time": "2023-02-11T08:58:19.591390Z" }, "cell_style": "split" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lowercase!\n" ] } ], "source": [ "# 又混乱又有产生 bug 的风险:\n", "c = 'a'\n", "if (c >= 'A') and (c <= 'Z'):\n", " print('Uppercase!')\n", "if (c >= 'a') and (c <= 'z'):\n", " print('lowercase!')\n", "if (c < 'A') or ((c > 'Z') and (c < 'a')) or (c > 'z'):\n", " print ('not a letter!')" ] }, { "cell_type": "code", "execution_count": null, "id": "d1085b80", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.374025Z", "start_time": "2023-02-11T08:41:12.374025Z" }, "cell_style": "split" }, "outputs": [], "source": [ "# 更好的做法:\n", "c = 'a'\n", "if (c >= 'A') and (c <= 'Z'):\n", " print('Uppercase!')\n", "elif (c >= 'a') and (c <= 'z'):\n", " print('lowercase!')\n", "else:\n", " print('not a letter!')" ] }, { "cell_type": "markdown", "id": "48991bac", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "使用一些 trick(如用算数逻辑来代替布尔逻辑)" ] }, { "cell_type": "code", "execution_count": null, "id": "91aeab66", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.375026Z", "start_time": "2023-02-11T08:41:12.375026Z" }, "cell_style": "split" }, "outputs": [], "source": [ "# 不清晰的:\n", "x = 42\n", "y = ((x > 0) and 99)" ] }, { "cell_type": "code", "execution_count": null, "id": "c009f14b", "metadata": { "ExecuteTime": { "end_time": "2023-02-11T08:41:12.377026Z", "start_time": "2023-02-11T08:41:12.377026Z" }, "cell_style": "split" }, "outputs": [], "source": [ "# 清晰的:\n", "x = 42\n", "if x > 0:\n", " y = 99" ] }, { "cell_type": "markdown", "id": "c39b51e5", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 总结\n", "\n", "- Conditionals Make Decisions.\n", "- if-else 结构构成了 Python 分支控制,if 还能嵌套使用。\n", "- 合理的编写风格会让代码更易读,还能尽可能避免引入 bug。" ] }, { "cell_type": "markdown", "id": "bcac0558", "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.9.15" }, "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 }