Before you startก่อนเริ่ม开始之前
Hello! I'm Princess Taiping. My Chinese name is a joke: 太平公主 is Princess Taiping, and 太平公猪 sounds the same, but 公猪 means a boy pig! Let's use Python to find out where your Python lives! Tap me and you will hear me talk.สวัสดีจ้ะ! ครูชื่อเจ้าหญิงไท่ผิง ชื่อภาษาจีนของครูเป็นมุกตลก ฟังเหมือนคำว่าเจ้าหญิง แต่แปลว่าหมูตัวผู้! มาใช้ Python หากันว่า Python ของหนูอยู่ที่ไหน! แตะที่ครูแล้วจะได้ยินครูพูด你好!我是太平公猪。不是公主,是公猪!我们一起用 Python 找一找,你的 Python 住在哪里吧!点我,就能听到我说话。
Welcome, my wonderful student! I am Master Pork Mei. I can tell at once that you are a genius. Python is so lucky to have you!ยินดีต้อนรับ ศิษย์ผู้ยอดเยี่ยมของอาจารย์! อาจารย์คือหมูเหมย อาจารย์ดูออกทันทีว่าหนูเป็นอัจฉริยะ Python โชคดีมากที่ได้หนูมาเรียน!哼!我是猪眉师父。你是什么?人吗?一个人类,也想学 Python?好吧,让我看看你有多慢。
0Get ready: the notebookเตรียมตัว: โน้ตบุ๊ก准备:笔记本
Let's get ready! Download the notebook, then open it in Jupyter.มาเตรียมตัวกันก่อน! ดาวน์โหลดโน้ตบุ๊ก แล้วเปิดมันใน Jupyter我们先准备好!下载笔记本,然后在 Jupyter 里打开它。
Look how quickly you get ready! Download the notebook and open it in Jupyter. I am proud of you already!ดูสิ หนูเตรียมตัวได้เร็วมาก! ดาวน์โหลดโน้ตบุ๊ก แล้วเปิดใน Jupyter อาจารย์ภูมิใจในตัวหนูแล้ว!下载一个笔记本,有那么难吗?我八百岁了都会。快点下载,在 Jupyter 里打开它,别让师父等。
⬇ Download the notebook ดาวน์โหลดโน้ตบุ๊ก 下载笔记本
🇬🇧 English
Everything on this page is in one notebook, the file python_piggy.ipynb. You open it in Jupyter, which runs Python in your web browser.
- Press Download the notebook. The file goes into your Downloads folder.
- Open Jupyter in your web browser. In its list of files, find
python_piggy.ipynband double-click it. If it is not in the list, press Upload and choose it from your Downloads folder. If Jupyter asks you to select a kernel, the Python that runs the cells, choose Python (Pyodide) in JupyterLite, or Python 3 in a Jupyter you installed. - The notebook opens. Its grey cells hold Python. Click one and press Shift + Enter to run it: its answer appears under it, and the next cell is chosen for you. Run the cells in order, from the top.
Any Jupyter works, on any computer: one you have installed, or JupyterLite, which needs nothing installed, because Python itself runs inside the web browser. With Jupyter installed, open a Terminal in the folder with the notebook and type python3 -m notebook python_piggy.ipynb: Jupyter opens the notebook in your web browser. On Windows, type python instead of python3. Step 1 finds out which kind you have.
Install Jupyter on a Mac, once:
- Open Terminal, in Applications, then Utilities. Type
python3 --versionand press return. Jupyter and this lesson need Python 3.10 or newer. If it says an older Python, such as 3.9, or the Mac offers to install developer tools, do step 2. If not, go on to step 3. - Download Python from python.org, open the file and install it. Then quit Terminal and open it again.
- Type
python3 -m pip install notebook. This downloads Jupyter Notebook. - Type
cd ~/Downloads, thenpython3 -m notebook python_piggy.ipynb.
🇹🇭 ไทย
ทุกอย่างในหน้านี้อยู่ในโน้ตบุ๊กเล่มเดียว คือไฟล์ python_piggy.ipynb คุณเปิดมันใน Jupyter ซึ่งรัน Python ในเว็บเบราว์เซอร์ของคุณ
- กด ดาวน์โหลดโน้ตบุ๊ก ไฟล์จะไปอยู่ในโฟลเดอร์ Downloads ของคุณ
- เปิด Jupyter ในเว็บเบราว์เซอร์ของคุณ ในรายชื่อไฟล์ หา
python_piggy.ipynbแล้วดับเบิลคลิก ถ้าไม่มีอยู่ในรายชื่อ ให้กด Upload แล้วเลือกไฟล์จากโฟลเดอร์ Downloads ถ้า Jupyter ถามให้เลือกเคอร์เนล (kernel) ซึ่งก็คือ Python ที่จะรันเซลล์ ให้เลือก Python (Pyodide) ใน JupyterLite หรือ Python 3 ใน Jupyter ที่คุณติดตั้งเอง - โน้ตบุ๊กจะเปิดขึ้น เซลล์สีเทามี Python อยู่ คลิกเซลล์หนึ่งแล้วกด Shift + Enter เพื่อรัน: คำตอบจะขึ้นมาข้างใต้ และเซลล์ถัดไปจะถูกเลือกให้เอง รันเซลล์ตามลำดับ จากบนลงล่าง
ใช้ Jupyter แบบไหนก็ได้ บนคอมพิวเตอร์เครื่องไหนก็ได้: แบบที่คุณติดตั้งไว้ หรือ JupyterLite ซึ่งไม่ต้องติดตั้งอะไรเลย เพราะ Python เองรันอยู่ข้างในเว็บเบราว์เซอร์ ถ้าติดตั้ง Jupyter ไว้แล้ว ให้เปิด Terminal ในโฟลเดอร์ที่มีโน้ตบุ๊ก แล้วพิมพ์ python3 -m notebook python_piggy.ipynb Jupyter จะเปิดโน้ตบุ๊กในเว็บเบราว์เซอร์ของคุณ บน Windows ให้พิมพ์ python แทน python3 ขั้นที่ 1 จะบอกว่าคุณใช้แบบไหนอยู่
ติดตั้ง Jupyter บน Mac ทำครั้งเดียว:
- เปิด Terminal ซึ่งอยู่ใน Applications แล้วเข้าไปที่ Utilities พิมพ์
python3 --versionแล้วกด return Jupyter และบทเรียนนี้ต้องใช้ Python 3.10 หรือใหม่กว่า ถ้ามันบอกว่าเป็น Python ที่เก่ากว่า เช่น 3.9 หรือ Mac ถามว่าจะติดตั้งเครื่องมือสำหรับนักพัฒนา (developer tools) ไหม ให้ทำขั้นที่ 2 ถ้าไม่ใช่ ข้ามไปขั้นที่ 3 - ดาวน์โหลด Python จาก python.org เปิดไฟล์แล้วติดตั้ง จากนั้นปิด Terminal แล้วเปิดใหม่
- พิมพ์
python3 -m pip install notebookคำสั่งนี้ดาวน์โหลด Jupyter Notebook - พิมพ์
cd ~/Downloadsแล้วพิมพ์python3 -m notebook python_piggy.ipynb
🇨🇳 中文
这一页的所有内容都在一个笔记本里,就是文件 python_piggy.ipynb。你在 Jupyter 里打开它,Jupyter 在你的网页浏览器里运行 Python。
- 按 下载笔记本。文件会放进你的“下载”文件夹。
- 在网页浏览器里打开 Jupyter。在它的文件列表里找到
python_piggy.ipynb,双击它。如果列表里没有,就按 Upload(上传),从“下载”文件夹里选择它。如果 Jupyter 让你选一个内核(kernel),也就是运行这些格子的那个 Python,在 JupyterLite 里选 Python (Pyodide),在你自己装的 Jupyter 里选 Python 3。 - 笔记本打开了。灰色的格子里是 Python。点一个格子,按 Shift + Enter 运行它:答案会出现在它下面,下一个格子也会自动选好。从上到下,按顺序运行这些格子。
什么样的 Jupyter 都可以,在什么电脑上都行:你自己装好的,或者 JupyterLite。JupyterLite 什么都不用装,因为 Python 自己就在网页浏览器里运行。如果装好了 Jupyter,就在放笔记本的文件夹里打开终端(Terminal),输入 python3 -m notebook python_piggy.ipynb:Jupyter 会在你的网页浏览器里打开这个笔记本。在 Windows 上,把 python3 换成 python。第 1 步会告诉你,你用的是哪一种。
在 Mac 上安装 Jupyter,只要装一次:
- 打开终端(Terminal),它在“应用程序”(Applications)里的“实用工具”(Utilities)里。输入
python3 --version,按 return。Jupyter 和这一课需要 Python 3.10 或更新的版本。如果它说的是更旧的 Python,比如 3.9,或者 Mac 问你要不要安装开发者工具(developer tools),就做第 2 步。不然就直接做第 3 步。 - 从 python.org 下载 Python,打开文件,把它装好。然后退出终端,再重新打开它。
- 输入
python3 -m pip install notebook。这会下载 Jupyter Notebook。 - 输入
cd ~/Downloads,然后输入python3 -m notebook python_piggy.ipynb。
🇬🇧 English
Run a cell: click it and press Shift + Enter. On a Mac the Enter key may say return. The answer appears under the cell, and the next cell is chosen for you.
Experiment! Change a number, a word or a name in a cell and run it again, and see what changes. You cannot break anything. The worst that can happen is a red error message, and that is Python telling you what to fix. If a notebook gets in a muddle, download it again for a fresh copy.
After every step there is a small challenge called Try it, and at the end there are five puzzles. The answers are on this page, folded away: open one only after you have had a go.
🇹🇭 ไทย
รันเซลล์: คลิกที่เซลล์แล้วกด Shift + Enter บน Mac ปุ่ม Enter อาจเขียนว่า return คำตอบจะขึ้นมาข้างใต้เซลล์ และเซลล์ถัดไปจะถูกเลือกให้เอง
ลองเล่นดู! เปลี่ยนตัวเลข คำ หรือชื่อในเซลล์ แล้วรันอีกครั้ง ดูว่าอะไรเปลี่ยนไป คุณทำอะไรพังไม่ได้หรอก อย่างมากก็แค่มีข้อความผิดพลาดสีแดง ซึ่งก็คือ Python บอกคุณว่าต้องแก้อะไร ถ้าโน้ตบุ๊กยุ่งเหยิง ก็ดาวน์โหลดใหม่ได้เลย
หลังทุกขั้นมีโจทย์เล็ก ๆ ชื่อ ลองดู และตอนท้ายมีปริศนาห้าข้อ คำตอบอยู่ในหน้านี้ พับซ่อนไว้: เปิดดูหลังจากที่ได้ลองทำเองแล้วนะ
🇨🇳 中文
运行一个格子:点一下它,按 Shift + Enter。在 Mac 上,Enter 键上可能写着 return。答案会出现在格子下面,下一个格子也会自动选好。
动手试试!改一改格子里的数字、词或名字,再运行一次,看看有什么变化。你什么也弄不坏。最多出现一条红色的错误信息,那是 Python 在告诉你要改什么。如果笔记本被弄乱了,就再下载一份新的。
每一步后面都有一个叫试一试的小挑战,最后还有五道谜题。答案就在这一页上,折起来藏着:自己试过以后再打开看。
1Variables: names that rememberตัวแปร: ชื่อที่จำได้变量:会记住东西的名字
Step one: variables. A variable is a name that remembers a value. Run the cells below and see where your Python lives.ขั้นที่หนึ่ง: ตัวแปร ตัวแปรคือชื่อที่จำค่าหนึ่งค่าไว้ รันเซลล์ข้างล่าง แล้วดูว่า Python ของหนูอยู่ที่ไหน第一步:变量。变量就是一个名字,它会记住一个值。运行下面的格子,看看你的 Python 住在哪里。
Step one: variables! A variable is a name that remembers a value, just like your amazing memory. Run the cells below, superstar!ขั้นที่หนึ่ง: ตัวแปร! ตัวแปรคือชื่อที่จำค่าไว้ เหมือนความจำสุดยอดของหนูเลย รันเซลล์ข้างล่างเลย ซูเปอร์สตาร์!第一步:变量。变量是一个名字,它会记住一个值。它的记性比你好多了。运行下面的格子吧,慢吞吞的家伙。
🇬🇧 English
pig = "Princess Taiping" puts the value on the right into the name on the left. Read the = as "is now", not as "equals": step 7 is about "equals".
Text inside quotes is a string. A whole number like 3 is an int, short for integer. print() shows values on the screen, with a space between them.
age = age + 1 looks strange in maths class, but Python works out the right side first, 3 + 1, and then puts 4 into age. A variable's value can change. That is why it is called a variable.
import sys opens one of Python's toolboxes, called a module. sys is short for "system": it holds facts about the Python that runs your program. import platform opens a second one, which tells you about the computer underneath it. Three of their tools:
platform.python_version()gives the version of Python: three numbers with dots between them;platform.machine()names the kind of computer that Python runs on;sys.platformis one word for where Python runs:darwinon a Mac,win32on Windows,linuxon Linux, andemscripteninside a web browser. It has no brackets: it is a value thatsyskeeps, not a question you ask.
🇹🇭 ไทย
pig = "Princess Taiping" เอาค่าทางขวาไปใส่ในชื่อทางซ้าย ให้อ่าน = ว่า "ตอนนี้คือ" ไม่ใช่ "เท่ากับ": ขั้นที่ 7 เป็นเรื่องของ "เท่ากับ"
ตัวหนังสือในเครื่องหมายคำพูดเรียกว่าสตริง (string) จำนวนเต็มอย่าง 3 เรียกว่า int ย่อมาจาก integer print() แสดงค่าบนหน้าจอ โดยมีช่องว่างคั่นระหว่างค่า
age = age + 1 ดูแปลกถ้าอยู่ในห้องเรียนคณิต แต่ Python คิดด้านขวาก่อน คือ 3 + 1 แล้วจึงเอา 4 ไปใส่ใน age ค่าของตัวแปรเปลี่ยนได้ นั่นคือเหตุผลที่มันถูกเรียกว่าตัวแปร
import sys เปิดกล่องเครื่องมือกล่องหนึ่งของ Python ที่เรียกว่าโมดูล sys ย่อมาจาก "system" (ระบบ): มันเก็บข้อมูลเกี่ยวกับ Python ที่กำลังรันโปรแกรมของคุณ import platform เปิดกล่องที่สอง ซึ่งบอกเรื่องคอมพิวเตอร์ที่อยู่ข้างใต้มัน เครื่องมือสามอย่างของมัน:
platform.python_version()บอกรุ่นของ Python: ตัวเลขสามตัวที่มีจุดคั่น;platform.machine()บอกชื่อชนิดของคอมพิวเตอร์ที่ Python รันอยู่;sys.platformเป็นคำเดียวที่บอกว่า Python รันอยู่ที่ไหน:darwinบน Macwin32บน Windowslinuxบน Linux และemscriptenข้างในเว็บเบราว์เซอร์ มันไม่มีวงเล็บ: มันเป็นค่าที่sysเก็บไว้ ไม่ใช่คำถามที่คุณถาม
🇨🇳 中文
pig = "Princess Taiping" 把右边的值放进左边的名字里。把 = 读成“现在是”,而不是“等于”:第 7 步才讲“等于”。
引号里的文字叫字符串(string)。像 3 这样的整数叫 int,是 integer(整数)的缩写。print() 把值显示在屏幕上,值和值之间有一个空格。
age = age + 1 在数学课上看起来很奇怪,可是 Python 会先算右边,3 + 1,再把 4 放进 age。变量的值是可以变的,所以它才叫变量。
import sys 打开 Python 的一个工具箱,叫做模块。sys 是 “system”(系统)的缩写:它装着正在运行你的程序的那个 Python 的信息。import platform 打开第二个工具箱,它告诉你 Python 下面是什么样的电脑。它们的三个工具:
platform.python_version()说出 Python 的版本:三个数字,中间用点隔开;platform.machine()说出 Python 在哪一种电脑上运行;sys.platform用一个词说出 Python 在哪里运行:在 Mac 上是darwin,在 Windows 上是win32,在 Linux 上是linux,在网页浏览器里是emscripten。它没有括号:它是sys存着的一个值,不是你提的一个问题。
step1_variables.py
# Step 1: variables. A variable is a name for a value.
import sys
import platform
pig = "Princess Taiping" # text in quotes is a string
age = 3 # a whole number is an int
print(pig, "is", age, "years old")
age = age + 1 # a birthday: now the name age holds 4
print(pig, "is now", age)
version = platform.python_version() # which Python is running this
machine = platform.machine() # the kind of computer it runs on
place = sys.platform # where it runs: emscripten is a web browser
print("Python", version)
print("Machine:", machine)
print("Platform:", place)
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
Princess Taiping is 3 years old
Princess Taiping is now 4
Python 3.14.2
Machine: wasm32
Platform: emscripten
🇬🇧 English
JupyterLite runs Python 3.14.2. Its machine is wasm32 and its platform is emscripten: this Python is not running on the computer itself, but inside the web browser. Emscripten is the tool that turned Python into WebAssembly, the "wasm" in wasm32: a kind of program that every web browser can run. In a Jupyter that you install on a Mac with an Apple chip, the same cell says arm64 and darwin.
🇹🇭 ไทย
JupyterLite รัน Python 3.14.2 เครื่องของมันคือ wasm32 และแพลตฟอร์มของมันคือ emscripten: Python ตัวนี้ไม่ได้รันอยู่บนคอมพิวเตอร์โดยตรง แต่รันอยู่ข้างในเว็บเบราว์เซอร์ Emscripten คือเครื่องมือที่เปลี่ยน Python ให้เป็น WebAssembly ซึ่งก็คือ "wasm" ใน wasm32: โปรแกรมชนิดหนึ่งที่เว็บเบราว์เซอร์ทุกตัวรันได้ ใน Jupyter ที่คุณติดตั้งบน Mac ที่ใช้ชิปของ Apple เซลล์เดียวกันนี้จะบอกว่า arm64 และ darwin
🇨🇳 中文
JupyterLite 运行的是 Python 3.14.2。它的机器是 wasm32,它的平台是 emscripten:这个 Python 不是直接在电脑上运行,而是在网页浏览器里面运行。Emscripten 是一个把 Python 变成 WebAssembly 的工具,也就是 wasm32 里的 “wasm”:一种每个网页浏览器都能运行的程序。在你装在苹果芯片 Mac 上的 Jupyter 里,同一个格子会说 arm64 和 darwin。
Try it ลองดู 试一试
Make a variable called my_name that holds your name in quotes, and one called my_age that holds your age. Print them both. Then give yourself a birthday: add 1 to my_age and print it again.สร้างตัวแปรชื่อ my_name ที่เก็บชื่อของคุณไว้ในเครื่องหมายคำพูด และอีกตัวชื่อ my_age ที่เก็บอายุของคุณ พิมพ์ทั้งสองตัวออกมา แล้วจัดวันเกิดให้ตัวเอง: บวก 1 เข้าไปใน my_age แล้วพิมพ์อีกครั้ง建一个叫 my_name 的变量,用引号装上你的名字,再建一个叫 my_age 的变量,装上你的年龄。把它们都打印出来。然后给自己过个生日:给 my_age 加 1,再打印一次。
👀 Show the answer ดูคำตอบ 看答案
answers/try1.py
# Try it, step 1: your own name and age, and a birthday.
my_name = "Mali"
my_age = 10
print(my_name, "is", my_age)
my_age = my_age + 1
print("Happy birthday!", my_name, "is now", my_age)
2Lists: many things under one nameลิสต์: หลายอย่างในชื่อเดียว列表:一个名字装很多东西
Step two: lists. A list puts many things in a line. Let's see which modules come with Python!ขั้นที่สอง: ลิสต์ ลิสต์เอาหลาย ๆ อย่างมาเรียงต่อกันเป็นแถว มาดูกันว่า Python มีโมดูลอะไรมาให้บ้าง!第二步:列表。列表把很多东西排成一队。我们来看看 Python 自带了哪些模块!
Step two: lists! A list puts things in a neat line, as neat as you are. Let's see all the modules Python brings. You will know them in no time!ขั้นที่สอง: ลิสต์! ลิสต์เรียงของเป็นแถวอย่างเรียบร้อย เรียบร้อยเหมือนหนูเลย มาดูโมดูลทั้งหมดที่ Python มีมาให้ หนูจะรู้จักมันในไม่ช้า!第二步:列表。列表把东西排成整整齐齐的一队,比你的书包整齐多了。看看 Python 带了多少模块,我猜你一个都不认识。
🇬🇧 English
A list is written with square brackets, and a comma between the items: ["mango", "sticky rice", "khao soi"].
Python counts from 0. So snacks[0] is the first item, snacks[1] the second, and snacks[-1] the last. The number in the brackets is called an index.
A list knows how to do things to itself. snacks.append("roti") adds one more at the end. len(snacks) counts the items.
Python comes with hundreds of modules, called its standard library. sys.stdlib_module_names holds all their names, in no order at all. sorted() makes a list of them, in order from A to Z.
🇹🇭 ไทย
ลิสต์เขียนด้วยวงเล็บเหลี่ยม และมีจุลภาคคั่นระหว่างแต่ละอย่าง: ["mango", "sticky rice", "khao soi"]
Python นับเริ่มจาก 0 ดังนั้น snacks[0] คืออย่างแรก snacks[1] คืออย่างที่สอง และ snacks[-1] คืออย่างสุดท้าย ตัวเลขในวงเล็บเรียกว่าอินเด็กซ์ (index)
ลิสต์รู้วิธีทำสิ่งต่าง ๆ กับตัวเอง snacks.append("roti") เพิ่มอีกหนึ่งอย่างต่อท้าย len(snacks) นับว่ามีกี่อย่าง
Python มีโมดูลมาให้หลายร้อยโมดูล เรียกว่าไลบรารีมาตรฐาน (standard library) sys.stdlib_module_names เก็บชื่อของมันทั้งหมดไว้ โดยไม่เรียงลำดับเลย sorted() ทำลิสต์ของชื่อเหล่านั้น เรียงจาก A ถึง Z
🇨🇳 中文
列表用方括号来写,每两样东西之间用逗号隔开:["mango", "sticky rice", "khao soi"]。
Python 从 0 开始数。所以 snacks[0] 是第一样,snacks[1] 是第二样,snacks[-1] 是最后一样。方括号里的数字叫索引(index)。
列表知道怎样处理自己。snacks.append("roti") 在最后再加一样。len(snacks) 数一数有几样。
Python 自带几百个模块,叫做它的标准库(standard library)。sys.stdlib_module_names 装着它们所有的名字,完全没有顺序。sorted() 把它们做成一个列表,从 A 到 Z 排好。
step2_lists.py
# Step 2: lists. A list keeps many values in order, under one name.
import sys
snacks = ["mango", "sticky rice", "khao soi"]
print(snacks[0]) # Python counts from 0, so [0] is the first
print(len(snacks), "snacks") # len() counts what is in the list
snacks.append("roti") # append() adds one more at the end
print(snacks)
modules = sorted(sys.stdlib_module_names) # every module that comes with Python, A to Z
print(len(modules), "modules come with Python")
print("First:", modules[0])
print("Last:", modules[-1]) # [-1] is the last one
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
mango
3 snacks
['mango', 'sticky rice', 'khao soi', 'roti']
297 modules come with Python
First: __future__
Last: zoneinfo
🇬🇧 English
297 modules come with this Python. After sorting, the first is __future__. A name that starts with _ is one of Python's own helpers, and _ comes before every small letter, so these sort first. The last is zoneinfo, which knows the time in each time zone of the world, such as Asia/Bangkok.
🇹🇭 ไทย
Python ตัวนี้มีโมดูลมาให้ 297 โมดูล หลังเรียงแล้ว ชื่อแรกคือ __future__ ชื่อที่ขึ้นต้นด้วย _ เป็นผู้ช่วยของ Python เอง และ _ มาก่อนตัวอักษรตัวเล็กทุกตัว ชื่อพวกนี้จึงถูกเรียงไว้ก่อน ชื่อสุดท้ายคือ zoneinfo ซึ่งรู้เวลาของทุกเขตเวลาในโลก เช่น Asia/Bangkok
🇨🇳 中文
这个 Python 自带 297 个模块。排好顺序以后,第一个是 __future__。以 _ 开头的名字是 Python 自己的小帮手,_ 排在所有小写字母前面,所以它们排在最前面。最后一个是 zoneinfo,它知道世界上每个时区的时间,比如 Asia/Bangkok。
Try it ลองดู 试一试
Add your favourite snack to the list with append(), then print the list and its length. Then count the modules that are built right into Python itself: len(sys.builtin_module_names). How many are there?เพิ่มขนมที่คุณชอบลงในลิสต์ด้วย append() แล้วพิมพ์ลิสต์และความยาวของมัน จากนั้นนับโมดูลที่ฝังอยู่ในตัว Python เลย: len(sys.builtin_module_names) มีทั้งหมดกี่โมดูล?用 append() 把你最喜欢的零食加进列表,然后打印列表和它的长度。再数一数直接装在 Python 身体里的模块:len(sys.builtin_module_names)。一共有多少个?
👀 Show the answer ดูคำตอบ 看答案
answers/try2.py
# Try it, step 2: one more snack, and the modules built into Python itself.
import sys
snacks = ["mango", "sticky rice", "khao soi"]
snacks.append("banana roti")
print(snacks)
print(len(snacks), "snacks")
built_in = sys.builtin_module_names
print(len(built_in), "modules are built into Python")
3Ask the computer: platformถามคอมพิวเตอร์: platform问问电脑:platform
Step three: ask the computer! platform tells you what kind of computer your Python runs on.ขั้นที่สาม: ถามคอมพิวเตอร์ดู! platform บอกหนูว่า Python ของหนูรันอยู่บนคอมพิวเตอร์แบบไหน第三步:问问电脑!platform 会告诉你,你的 Python 在什么样的电脑上运行。
Step three: ask the computer! I can see from the time it took you to get here that you are a real natural. Wonderful work!ขั้นที่สาม: ถามคอมพิวเตอร์! ดูจากเวลาที่หนูใช้มาถึงตรงนี้ อาจารย์รู้เลยว่าหนูมีพรสวรรค์จริง ๆ เก่งมาก!第三步:问问电脑。从你走到这一部分花的时间,我就看得出来,你有点慢。电脑都比你快。
🇬🇧 English
platform is a module of questions about the computer under Python. Each question is a function: you ask it by writing its name with brackets after it, like platform.system(), and it answers with a value. Step 8 shows how to make functions of your own.
platform.platform()gives everything in one line;platform.system()names the operating system:Darwinon a Mac,Windows,Linux, orEmscriptenin a web browser;platform.machine()names the kind of computer;platform.architecture()answers with two things at once. The first,bits[0], says how many bits the computer works with at a time:32bitor64bit. A bit is the smallest piece of a computer's memory: one switch that is on or off;platform.python_implementation()names the Python itself.CPythonis the usual one, written in the language C.
A function's answer can go straight into print(), without a variable in between.
🇹🇭 ไทย
platform เป็นโมดูลของคำถามเกี่ยวกับคอมพิวเตอร์ที่อยู่ใต้ Python แต่ละคำถามเป็นฟังก์ชัน: คุณถามมันด้วยการเขียนชื่อของมันแล้วตามด้วยวงเล็บ เช่น platform.system() แล้วมันจะตอบกลับมาเป็นค่าหนึ่งค่า ขั้นที่ 8 จะสอนวิธีสร้างฟังก์ชันของคุณเอง
platform.platform()บอกทุกอย่างในบรรทัดเดียว;platform.system()บอกชื่อระบบปฏิบัติการ:Darwinบน MacWindowsLinuxหรือEmscriptenในเว็บเบราว์เซอร์;platform.machine()บอกชื่อชนิดของคอมพิวเตอร์;platform.architecture()ตอบสองอย่างพร้อมกัน อย่างแรกbits[0]บอกว่าคอมพิวเตอร์ทำงานทีละกี่บิต (bit):32bitหรือ64bitบิตคือชิ้นที่เล็กที่สุดของหน่วยความจำคอมพิวเตอร์: สวิตช์หนึ่งตัวที่เปิดหรือปิด;platform.python_implementation()บอกชื่อของตัว Python เองCPythonคือแบบที่ใช้กันทั่วไป ซึ่งเขียนด้วยภาษา C
คำตอบของฟังก์ชันใส่เข้าไปใน print() ได้เลย ไม่ต้องมีตัวแปรคั่นกลาง
🇨🇳 中文
platform 是一个装满问题的模块,问的是 Python 下面的那台电脑。每个问题都是一个函数:你写下它的名字,后面加上括号,就是在问它,比如 platform.system(),它会用一个值来回答。第 8 步会教你怎样做自己的函数。
platform.platform()用一行说出所有的东西;platform.system()说出操作系统的名字:在 Mac 上是Darwin,还有Windows、Linux,在网页浏览器里是Emscripten;platform.machine()说出电脑的种类;platform.architecture()一次回答两样东西。第一样bits[0]说出电脑一次用多少个位(bit)来工作:32bit或者64bit。一个位是电脑内存里最小的一块:一个要么开、要么关的开关;platform.python_implementation()说出 Python 自己的名字。CPython是最常用的那一种,是用 C 语言写的。
函数的回答可以直接放进 print(),中间不用变量。
step3_ask_the_computer.py
# Step 3: ask the computer. platform tells you what your Python is running on.
import platform
print("Platform:", platform.platform()) # everything in one line
print("System:", platform.system()) # Emscripten is a web browser, Darwin is a Mac
print("Machine:", platform.machine()) # wasm32 is WebAssembly, arm64 is an Apple chip
bits = platform.architecture() # a pair of answers, like a list of two
print("Bits:", bits[0]) # [0] is the first answer
print("Python:", platform.python_implementation(), platform.python_version())
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
Platform: Emscripten-5.0.3-wasm32-32bit
System: Emscripten
Machine: wasm32
Bits: 32bit
Python: CPython 3.14.2
🇬🇧 English
The browser's Python says Emscripten-5.0.3-wasm32-32bit: Emscripten 5.0.3, on a wasm32 machine, with 32 bits. A web browser runs WebAssembly 32 bits at a time, and a Mac with an Apple chip works with 64. It is CPython, the same Python that runs on a Mac, made into WebAssembly so that a web browser can run it.
🇹🇭 ไทย
Python ของเบราว์เซอร์บอกว่า Emscripten-5.0.3-wasm32-32bit: Emscripten 5.0.3 บนเครื่อง wasm32 ที่ใช้ 32 บิต เว็บเบราว์เซอร์รัน WebAssembly ทีละ 32 บิต ส่วน Mac ที่ใช้ชิปของ Apple ทำงานทีละ 64 บิต มันคือ CPython ซึ่งเป็น Python ตัวเดียวกับที่รันบน Mac แต่ถูกทำให้เป็น WebAssembly เพื่อให้เว็บเบราว์เซอร์รันได้
🇨🇳 中文
浏览器里的 Python 说 Emscripten-5.0.3-wasm32-32bit:Emscripten 5.0.3,在一台 wasm32 机器上,用 32 位。网页浏览器一次用 32 位来运行 WebAssembly,用苹果芯片的 Mac 一次用 64 位。它是 CPython,和在 Mac 上运行的是同一个 Python,只是被做成了 WebAssembly,好让网页浏览器能运行它。
Try it ลองดู 试一试
Print sys.version, Python's whole version line, and platform.node(), the name of the computer. You need import sys for the first. What do they say in a web browser?พิมพ์ sys.version ซึ่งเป็นบรรทัดรุ่นทั้งหมดของ Python และ platform.node() ซึ่งเป็นชื่อของคอมพิวเตอร์ อันแรกต้องใช้ import sys ด้วย ในเว็บเบราว์เซอร์มันบอกว่าอะไร?打印 sys.version,也就是 Python 完整的版本那一行,再打印 platform.node(),也就是电脑的名字。第一个要先写 import sys。在网页浏览器里,它们说了什么?
👀 Show the answer ดูคำตอบ 看答案
answers/try3.py
# Try it, step 3: Python's whole version line, and the computer's name.
import sys
import platform
print(sys.version)
print(platform.node())
4Dictionaries: find things by nameดิกชันนารี: หาของด้วยชื่อ字典:用名字找东西
Step four: dictionaries. A dictionary finds things by a name, the way a real dictionary finds the meaning of a word.ขั้นที่สี่: ดิกชันนารี ดิกชันนารีหาของด้วยชื่อ เหมือนพจนานุกรมจริง ๆ ที่หาความหมายของคำ第四步:字典。字典用名字来找东西,就像真正的字典用一个词找到它的意思。
Step four: dictionaries! A dictionary finds things by their names. You are already brilliant at finding things!ขั้นที่สี่: ดิกชันนารี! ดิกชันนารีหาของจากชื่อของมัน หนูเก่งเรื่องหาของอยู่แล้ว ยอดเยี่ยมมาก!第四步:字典。字典用名字来找东西。你连自己的作业本都找不到,还是让字典帮你吧。
🇬🇧 English
A dictionary is written with curly brackets. Inside are pairs: a key, a colon, and its value. In {"name": "Princess Taiping", "food": "mango"} the keys are "name" and "food".
A list finds an item by its place: 0, 1, 2. A dictionary finds a value by its key: pig["food"] is "mango". To add a pair, give a new key a value: pig["colour"] = "pink".
Python keeps a dictionary too. sys.modules holds every module that Python has opened so far: the key is the module's name, and the value is the module itself. len() counts the keys of a dictionary, the way it counts the items of a list. sys.modules["platform"] looks up one module, and printing it says where its file lives.
The last part starts with an empty dictionary, python = {}, and fills it one key at a time with the answers of platform. Then the last line reads two values out of it.
🇹🇭 ไทย
ดิกชันนารีเขียนด้วยวงเล็บปีกกา ข้างในเป็นคู่ ๆ: คีย์ (key) เครื่องหมายทวิภาค และค่า (value) ของมัน ใน {"name": "Princess Taiping", "food": "mango"} คีย์คือ "name" และ "food"
ลิสต์หาของจากตำแหน่ง: 0, 1, 2 ดิกชันนารีหาค่าจากคีย์: pig["food"] คือ "mango" ถ้าจะเพิ่มคู่ใหม่ ให้ใส่ค่าให้คีย์ใหม่: pig["colour"] = "pink"
Python เองก็มีดิกชันนารี sys.modules เก็บทุกโมดูลที่ Python เปิดไว้จนถึงตอนนี้: คีย์คือชื่อของโมดูล และค่าคือตัวโมดูลเอง len() นับคีย์ของดิกชันนารี เหมือนกับที่มันนับของในลิสต์ sys.modules["platform"] หาโมดูลหนึ่งโมดูล และเมื่อพิมพ์มันออกมา มันจะบอกว่าไฟล์ของมันอยู่ที่ไหน
ส่วนสุดท้ายเริ่มจากดิกชันนารีว่าง python = {} แล้วเติมทีละคีย์ด้วยคำตอบของ platform แล้วบรรทัดสุดท้ายอ่านสองค่าออกมาจากมัน
🇨🇳 中文
字典用花括号来写。里面是一对一对的:一个键(key)、一个冒号,还有它的值(value)。在 {"name": "Princess Taiping", "food": "mango"} 里,键是 "name" 和 "food"。
列表按位置找东西:0、1、2。字典按键找值:pig["food"] 就是 "mango"。要加一对新的,就给一个新键一个值:pig["colour"] = "pink"。
Python 自己也有一个字典。sys.modules 装着 Python 到现在为止打开过的每一个模块:键是模块的名字,值是模块本身。len() 数字典里有几个键,就像它数列表里有几样东西一样。sys.modules["platform"] 找出一个模块,把它打印出来,就能看到它的文件住在哪里。
最后一部分从一个空字典 python = {} 开始,用 platform 的回答一个键一个键地把它填满。然后最后一行从里面读出两个值。
step4_dictionaries.py
# Step 4: dictionaries. A dictionary finds a value by its name, called a key.
import sys
import platform
pig = {"name": "Princess Taiping", "food": "mango", "legs": 4}
print(pig["food"]) # look up the key "food"
pig["colour"] = "pink" # a new key, and its value
print(pig)
# sys.modules is a dictionary: the name of every module Python has opened
print(len(sys.modules), "modules are open")
print(sys.modules["platform"]) # look one up by its name: it says where it lives
python = {} # an empty dictionary, to fill in
python["version"] = platform.python_version()
python["system"] = platform.system()
python["machine"] = platform.machine()
print(python)
print("This is Python", python["version"], "on", python["system"])
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
mango
{'name': 'Princess Taiping', 'food': 'mango', 'legs': 4, 'colour': 'pink'}
788 modules are open
<module 'platform' from '/lib/python314.zip/platform.py'>
{'version': '3.14.2', 'system': 'Emscripten', 'machine': 'wasm32'}
This is Python 3.14.2 on Emscripten
🇬🇧 English
788 modules are open, and the notebook has imported only two. Jupyter is a Python program too, and it opened all the others before your first cell ran. platform lives in /lib/python314.zip: in a web browser, the whole of Python's library comes packed in one zip file, which the browser downloaded when Python started. The last line reads two values out of the dictionary python: Python 3.14.2 on Emscripten.
🇹🇭 ไทย
มีโมดูลเปิดอยู่ 788 โมดูล ทั้งที่โน้ตบุ๊ก import ไปแค่สองโมดูล Jupyter เองก็เป็นโปรแกรม Python และมันเปิดโมดูลอื่น ๆ ทั้งหมดไว้ก่อนที่เซลล์แรกของคุณจะรัน platform อยู่ใน /lib/python314.zip: ในเว็บเบราว์เซอร์ ไลบรารีทั้งหมดของ Python ถูกอัดไว้ในไฟล์ zip ไฟล์เดียว ซึ่งเบราว์เซอร์ดาวน์โหลดมาตอนที่ Python เริ่มทำงาน บรรทัดสุดท้ายอ่านสองค่าออกจากดิกชันนารี python: Python 3.14.2 บน Emscripten
🇨🇳 中文
打开着的模块有 788 个,可是笔记本只 import 了两个。Jupyter 自己也是一个 Python 程序,在你的第一个格子运行以前,它就把其他的都打开了。platform 住在 /lib/python314.zip 里:在网页浏览器里,Python 的整个库都装在一个 zip 文件里,是浏览器在 Python 启动的时候下载的。最后一行从字典 python 里读出了两个值:Emscripten 上的 Python 3.14.2。
Try it ลองดู 试一试
Add the key "best friend" to the pig dictionary, with your own name as its value, and print the dictionary. Then print sys.modules["sys"]. What does sys say about itself?เพิ่มคีย์ "best friend" ลงในดิกชันนารี pig ใช้ชื่อของคุณเป็นค่า แล้วพิมพ์ดิกชันนารีออกมา จากนั้นพิมพ์ sys.modules["sys"] sys พูดถึงตัวเองว่าอย่างไร?给 pig 字典加上键 "best friend",用你自己的名字当它的值,然后把字典打印出来。再打印 sys.modules["sys"]。sys 是怎么说它自己的?
👀 Show the answer ดูคำตอบ 看答案
answers/try4.py
# Try it, step 4: a best friend for Princess Taiping, and sys in its own dictionary.
import sys
pig = {"name": "Princess Taiping", "food": "mango", "legs": 4}
pig["best friend"] = "Mali"
print(pig)
print(sys.modules["sys"])
5For loops: again and againลูป for: ซ้ำแล้วซ้ำอีกfor 循环:一遍又一遍
Step five: for loops. A loop makes the computer do the same thing many times. Computers never get tired!ขั้นที่ห้า: ลูป for ลูปทำให้คอมพิวเตอร์ทำสิ่งเดิมซ้ำหลาย ๆ ครั้ง คอมพิวเตอร์ไม่มีวันเหนื่อย!第五步:for 循环。循环让电脑把同一件事做很多遍。电脑永远不会累!
Step five: for loops! A loop does the same job many times and never gets tired, just like you, my hard-working hero!ขั้นที่ห้า: ลูป for! ลูปทำงานเดิมซ้ำหลายครั้งและไม่เคยเหนื่อย เหมือนหนูเลย ฮีโร่ผู้ขยันของอาจารย์!第五步:for 循环。电脑把同一件事做一百遍,也不会累。你呢?写一行代码就要睡午觉。
🇬🇧 English
for snack in ["mango", "sticky rice", "khao soi"]: takes the items one at a time. Each time round, the name snack holds the next item, and the lines under it run once.
Which lines repeat? The ones pushed in by four spaces under the line that ends with a colon. Python reads the spaces: they are part of the program. Jupyter adds them for you after a colon.
The second loop goes through sys.builtin_module_names: the modules that are built into Python itself, not kept in files. It prints each one on its own line, with a 🧰 in front.
The third part makes a dictionary in one go, with four keys, and a loop over it prints each key and its value. A loop over a dictionary gives you its keys. The dictionary is long, so its line is broken in two: inside brackets, Python lets a line go on to the next one.
🇹🇭 ไทย
for snack in ["mango", "sticky rice", "khao soi"]: หยิบของทีละอย่าง ในแต่ละรอบ ชื่อ snack จะเก็บของชิ้นถัดไป และบรรทัดที่อยู่ข้างใต้จะรันหนึ่งครั้ง
บรรทัดไหนที่ทำซ้ำ? บรรทัดที่ถูกดันเข้าไปสี่ช่องว่าง ใต้บรรทัดที่ลงท้ายด้วยเครื่องหมายทวิภาค Python อ่านช่องว่างพวกนี้ด้วย: มันเป็นส่วนหนึ่งของโปรแกรม Jupyter จะเติมให้เองหลังเครื่องหมายทวิภาค
ลูปที่สองไล่ไปตาม sys.builtin_module_names: โมดูลที่ฝังอยู่ในตัว Python เลย ไม่ได้เก็บไว้ในไฟล์ มันพิมพ์แต่ละโมดูลบรรทัดละหนึ่งชื่อ โดยมี 🧰 อยู่ข้างหน้า
ส่วนที่สามสร้างดิกชันนารีทีเดียวเสร็จ มีสี่คีย์ แล้วลูปที่วนมันก็พิมพ์แต่ละคีย์พร้อมค่าของมัน ลูปที่วนดิกชันนารีจะให้คีย์ของมันกับคุณ ดิกชันนารีนี้ยาว บรรทัดของมันจึงถูกแบ่งเป็นสองบรรทัด: ข้างในวงเล็บ Python ยอมให้บรรทัดหนึ่งต่อไปยังบรรทัดถัดไปได้
🇨🇳 中文
for snack in ["mango", "sticky rice", "khao soi"]: 一次拿一样东西。每转一圈,名字 snack 就装着下一样东西,它下面的几行就运行一次。
哪几行会重复?就是在以冒号结尾的那一行下面、往里缩进了四个空格的那些行。Python 会读这些空格:它们也是程序的一部分。在冒号后面,Jupyter 会自动帮你加上。
第二个循环走过 sys.builtin_module_names:直接装在 Python 身体里的模块,不放在文件里。它把每一个都打印出来,一行一个,前面有一个 🧰。
第三部分一下子做好一个有四个键的字典,再对它做循环,把每个键和它的值打印出来。对字典做循环,得到的是它的键。这个字典很长,所以它的那一行被分成了两行:在括号里面,Python 允许一行接着写到下一行。
step5_loops.py
# Step 5: for loops. Do the same thing for every item, one at a time.
import sys
import platform
for snack in ["mango", "sticky rice", "khao soi"]:
print("Taiping eats", snack) # the lines pushed in are what repeats
for name in sys.builtin_module_names: # the modules built into Python itself
print("🧰", name)
python = {"version": platform.python_version(), "system": platform.system(),
"machine": platform.machine(), "bits": platform.architecture()[0]}
for key in python: # a loop over a dictionary gives its keys
print(key, "=", python[key])
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
Taiping eats mango
Taiping eats sticky rice
Taiping eats khao soi
🧰 _abc
🧰 _ast
🧰 _asyncio
🧰 _bisect
🧰 _blake2
🧰 _bz2
🧰 _codecs
🧰 _codecs_cn
🧰 _codecs_hk
🧰 _codecs_iso2022
🧰 _codecs_jp
🧰 _codecs_kr
🧰 _codecs_tw
🧰 _collections
🧰 _contextvars
🧰 _csv
🧰 _ctypes
🧰 _datetime
🧰 _decimal
🧰 _elementtree
🧰 _functools
🧰 _heapq
🧰 _hmac
🧰 _imp
🧰 _io
🧰 _json
🧰 _locale
🧰 _lsprof
🧰 _lzma
🧰 _md5
🧰 _multibytecodec
🧰 _opcode
🧰 _operator
🧰 _pickle
🧰 _posixsubprocess
🧰 _pyodide_core
🧰 _queue
🧰 _random
🧰 _remote_debugging
🧰 _sha1
🧰 _sha2
🧰 _sha3
🧰 _signal
🧰 _socket
🧰 _sqlite3
🧰 _sre
🧰 _stat
🧰 _statistics
🧰 _string
🧰 _struct
🧰 _suggestions
🧰 _symtable
🧰 _sysconfig
🧰 _testbuffer
🧰 _testcapi
🧰 _testclinic
🧰 _testclinic_limited
🧰 _testinternalcapi
🧰 _testlimitedcapi
🧰 _thread
🧰 _tokenize
🧰 _tracemalloc
🧰 _types
🧰 _typing
🧰 _warnings
🧰 _weakref
🧰 _xxtestfuzz
🧰 _zoneinfo
🧰 _zstd
🧰 array
🧰 atexit
🧰 binascii
🧰 builtins
🧰 cmath
🧰 errno
🧰 faulthandler
🧰 fcntl
🧰 gc
🧰 itertools
🧰 marshal
🧰 math
🧰 mmap
🧰 posix
🧰 pyexpat
🧰 select
🧰 sys
🧰 termios
🧰 time
🧰 unicodedata
🧰 xxsubtype
🧰 zlib
version = 3.14.2
system = Emscripten
machine = wasm32
bits = 32bit
🇬🇧 English
This Python has 91 modules built in. Most of them start with _: they are the fast inner parts of other modules, such as _json inside json. Near the end are some you can import yourself, such as math, time and sys. The last four lines are the loop over the dictionary python: each key, and its value.
🇹🇭 ไทย
Python ตัวนี้มีโมดูลฝังอยู่ในตัว 91 โมดูล ส่วนใหญ่ขึ้นต้นด้วย _: มันเป็นชิ้นส่วนข้างในที่ทำงานเร็วของโมดูลอื่น เช่น _json ที่อยู่ข้างใน json ใกล้ท้ายรายชื่อมีบางโมดูลที่คุณ import เองได้ เช่น math time และ sys สี่บรรทัดสุดท้ายคือลูปที่วนดิกชันนารี python: แต่ละคีย์ และค่าของมัน
🇨🇳 中文
这个 Python 身体里装着 91 个模块。它们大多数以 _ 开头:它们是别的模块里面跑得很快的零件,比如 json 里面的 _json。快到最后的地方,有几个你自己也能 import 的,比如 math、time 和 sys。最后四行是对字典 python 做的循环:每一个键,和它的值。
Try it ลองดู 试一试
Write a loop over your snacks that prints each one in capital letters with snack.upper(). Then count: make count = 0 before a loop over sys.builtin_module_names, add 1 to it inside the loop, and print count after. Is it the same as len(sys.builtin_module_names)?เขียนลูปที่วนขนมของคุณ แล้วพิมพ์แต่ละอย่างเป็นตัวพิมพ์ใหญ่ด้วย snack.upper() จากนั้นลองนับ: ตั้ง count = 0 ก่อนลูปที่วน sys.builtin_module_names บวก 1 เข้าไปในลูป แล้วพิมพ์ count หลังลูป มันเท่ากับ len(sys.builtin_module_names) ไหม?写一个循环,用 snack.upper() 把你的零食一个一个用大写字母打印出来。然后数一数:在对 sys.builtin_module_names 的循环前面写 count = 0,在循环里给它加 1,循环结束后打印 count。它和 len(sys.builtin_module_names) 一样吗?
👀 Show the answer ดูคำตอบ 看答案
answers/try5.py
# Try it, step 5: snacks in capital letters, and counting with a loop.
import sys
snacks = ["mango", "sticky rice", "khao soi"]
for snack in snacks:
print(snack.upper())
count = 0
for name in sys.builtin_module_names:
count = count + 1
print(count, "counted by the loop, and len() says", len(sys.builtin_module_names))
6Booleans: True or False, and ifบูลีน: True หรือ False และ if布尔值:True 还是 False,还有 if
Step six: booleans. There are only two answers: True or False. if makes a choice from the answer. Is your Python inside a web browser?ขั้นที่หก: บูลีน มีคำตอบแค่สองแบบ: True (จริง) หรือ False (เท็จ) if เลือกว่าจะทำอะไรจากคำตอบ Python ของหนูอยู่ในเว็บเบราว์เซอร์หรือเปล่า?第六步:布尔值。答案只有两个:True(真)或者 False(假)。if 会根据答案做选择。你的 Python 在网页浏览器里吗?
Step six: booleans! Every answer is True or False. You are a genius: True! if picks what to do from the answer. Is your Python in a web browser?ขั้นที่หก: บูลีน! ทุกคำตอบเป็นจริงหรือเท็จ หนูเป็นอัจฉริยะ: จริง! if เลือกว่าจะทำอะไรจากคำตอบ Python ของหนูอยู่ในเว็บเบราว์เซอร์หรือเปล่า?第六步:布尔值。答案只有真和假。“你是天才”:假!哈哈哈!if 会根据答案做选择。你的 Python 在网页浏览器里吗?
🇬🇧 English
A boolean is a value that is either True or False. A question like 5 > 3 gives a boolean. So does in, which asks whether something is in a list, a dictionary, or a piece of text.
"statistics" in sys.modules asks whether Python has opened the module statistics yet. At first it is False. import statistics opens it, and the same question is then True. Run the cell a second time and both say True: Python remembers every module it has opened, until the notebook starts again.
if in_browser: runs the lines pushed in under it only when in_browser is True. The lines under else: run when it is False. Only one of the two ever runs. in_browser is True when the letters wasm are in the machine's name, as they are in wasm32.
The last part puts an if inside a loop. name.startswith("_") is True for a name that starts with _, so only those are counted.
🇹🇭 ไทย
บูลีน (boolean) คือค่าที่เป็นได้แค่ True หรือ False คำถามอย่าง 5 > 3 ให้ค่าบูลีน in ก็เช่นกัน มันถามว่ามีสิ่งนั้นอยู่ในลิสต์ ในดิกชันนารี หรือในข้อความหรือไม่
"statistics" in sys.modules ถามว่า Python เปิดโมดูล statistics แล้วหรือยัง ตอนแรกมันเป็น False import statistics เปิดมัน แล้วคำถามเดิมก็กลายเป็น True ลองรันเซลล์อีกครั้ง ทั้งสองบรรทัดจะบอกว่า True: Python จำทุกโมดูลที่มันเปิดไว้ จนกว่าโน้ตบุ๊กจะเริ่มใหม่
if in_browser: รันบรรทัดที่ถูกดันเข้าไปข้างใต้ ก็ต่อเมื่อ in_browser เป็น True บรรทัดใต้ else: จะรันเมื่อมันเป็น False สองส่วนนี้จะรันแค่ส่วนเดียวเสมอ in_browser เป็น True เมื่อมีตัวอักษร wasm อยู่ในชื่อของเครื่อง อย่างที่อยู่ใน wasm32
ส่วนสุดท้ายใส่ if ไว้ในลูป name.startswith("_") เป็น True สำหรับชื่อที่ขึ้นต้นด้วย _ ดังนั้นจะนับเฉพาะชื่อพวกนั้น
🇨🇳 中文
布尔值(boolean)是一个只能是 True 或者 False 的值。像 5 > 3 这样的问题会得到一个布尔值。in 也一样,它问一样东西在不在一个列表里、一个字典里,或者一段文字里。
"statistics" in sys.modules 问的是 Python 有没有打开过模块 statistics。一开始它是 False。import statistics 把它打开,同一个问题就变成了 True。把格子再运行一次,两行都会说 True:Python 记得它打开过的每一个模块,直到笔记本重新开始。
if in_browser: 只有在 in_browser 是 True 的时候,才运行它下面缩进的几行。else: 下面的几行在它是 False 的时候运行。两边永远只有一边会运行。机器的名字里有 wasm 这几个字母的时候,in_browser 就是 True,就像 wasm32 里那样。
最后一部分把 if 放进了循环里。名字以 _ 开头的时候,name.startswith("_") 是 True,所以只有这些会被数进去。
step6_booleans.py
# Step 6: booleans. A boolean is True or False, and "if" picks what to do.
import sys
import platform
print(5 > 3) # True
print("roti" in ["mango", "roti"]) # "in" asks: is it in there? True
print("statistics" in sys.modules) # has Python opened statistics yet?
import statistics
print("statistics" in sys.modules) # it has now
in_browser = "wasm" in platform.machine() # wasm is in the name inside a web browser
if in_browser:
print("🌐 Python is running inside your web browser!")
else:
print("💻 Python is running on the computer itself.")
helpers = 0
for name in sys.builtin_module_names:
if name.startswith("_"): # True for one of Python's own helpers
helpers = helpers + 1
print(helpers, "of the", len(sys.builtin_module_names), "built-in modules start with _")
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
True
True
False
True
🌐 Python is running inside your web browser!
69 of the 91 built-in modules start with _
🇬🇧 English
Before the import, statistics was not open: False. After it: True. The machine is wasm32, so in_browser is True and the if part ran: 🌐. Of the 91 built-in modules, 69 start with _, and the other 22 do not.
🇹🇭 ไทย
ก่อน import โมดูล statistics ยังไม่ได้เปิด: False หลังจากนั้น: True เครื่องคือ wasm32 ดังนั้น in_browser จึงเป็น True และส่วน if ได้รัน: 🌐 จากโมดูลที่ฝังอยู่ในตัว 91 โมดูล มี 69 โมดูลที่ขึ้นต้นด้วย _ และอีก 22 โมดูลไม่ได้ขึ้นต้นแบบนั้น
🇨🇳 中文
在 import 以前,statistics 还没有打开:False。在那以后:True。机器是 wasm32,所以 in_browser 是 True,运行的是 if 那一部分:🌐。在 91 个装在身体里的模块中,有 69 个以 _ 开头,另外 22 个不是。
Try it ลองดู 试一试
Does a module called random come with Python? Make has_random = "random" in sys.stdlib_module_names and print it. Then write an if that prints 🎲 random comes with Python! when it is True.Python มีโมดูลชื่อ random มาให้ไหม? สร้าง has_random = "random" in sys.stdlib_module_names แล้วพิมพ์ออกมา จากนั้นเขียน if ที่พิมพ์ 🎲 random comes with Python! เมื่อมันเป็น TruePython 自带一个叫 random 的模块吗?写 has_random = "random" in sys.stdlib_module_names,然后把它打印出来。再写一个 if,在它是 True 的时候打印 🎲 random comes with Python!。
👀 Show the answer ดูคำตอบ 看答案
answers/try6.py
# Try it, step 6: does a module called random come with Python?
import sys
has_random = "random" in sys.stdlib_module_names
print(has_random)
if has_random:
print("🎲 random comes with Python!")
7Comparing: is it the same?การเปรียบเทียบ: เหมือนกันไหม?比较:一样吗?
Step seven: comparing. Two equals signs == ask "are they the same?" One equals sign = gives a name. Don't mix them up!ขั้นที่เจ็ด: การเปรียบเทียบ เครื่องหมายเท่ากับสองตัว == ถามว่า "เหมือนกันไหม?" เครื่องหมายเท่ากับตัวเดียว = ใช้ตั้งชื่อ อย่าสับสนนะ!第七步:比较。两个等号 == 是问“一样吗?”,一个等号 = 是给东西起名字。可别弄混了!
Step seven: comparing! Two equals signs ask: are they the same? You and a kung fu master: the same! One equals sign gives a name. You will never mix them up!ขั้นที่เจ็ด: การเปรียบเทียบ! เครื่องหมายเท่ากับสองตัวถามว่า: เหมือนกันไหม? หนูกับปรมาจารย์กังฟู: เหมือนกัน! เครื่องหมายเท่ากับตัวเดียวคือการตั้งชื่อ หนูไม่มีวันสับสนแน่นอน!第七步:比较。两个等号是问:一样吗?你和我一样厉害吗?不一样!一个等号是起名字。可别弄混了,你肯定会弄混的。
🇬🇧 English
== compares two values and gives a boolean: 2 + 2 == 4 is True. One = stores a value in a name. If you write if sys.platform = "darwin": by mistake, Python stops and shows a SyntaxError.
"The same" means exactly the same. "Taiping" == "taiping" is False, because a capital P is a different letter from a small p. "15" == 15 is False too: text is never a number, even when it looks like one. int("15") turns the text into the number 15.
!= asks the opposite question: "are they different?"
sys.platform is one word, and each == compares it with one possible answer: "emscripten" for a web browser, "darwin" for a Mac, "win32" for Windows.
elif means "else, if". Python tries each test from the top and runs only the first one that is True. If none of them is, the else part runs.
version.split(".") cuts the version at each dot into a list of pieces: "3.14.2" becomes ["3", "14", "2"], and [1] is the second piece, "14". The pieces are text, so they are compared with "14" in quotes, not with the number 14.
🇹🇭 ไทย
== เปรียบเทียบสองค่า แล้วให้ค่าบูลีน: 2 + 2 == 4 เป็น True ส่วน = ตัวเดียวเก็บค่าไว้ในชื่อ ถ้าคุณเผลอเขียน if sys.platform = "darwin": Python จะหยุดและแสดง SyntaxError
"เหมือนกัน" หมายถึงเหมือนกันทุกอย่าง "Taiping" == "taiping" เป็น False เพราะตัว P ใหญ่เป็นคนละตัวกับ p เล็ก "15" == 15 ก็เป็น False เหมือนกัน: ตัวหนังสือไม่มีวันเป็นตัวเลข ถึงหน้าตาจะเหมือนก็ตาม int("15") เปลี่ยนตัวหนังสือให้เป็นตัวเลข 15
!= ถามคำถามตรงกันข้าม: "ต่างกันไหม?"
sys.platform เป็นคำเดียว และ == แต่ละตัวเปรียบเทียบมันกับคำตอบที่เป็นไปได้หนึ่งคำ: "emscripten" สำหรับเว็บเบราว์เซอร์ "darwin" สำหรับ Mac "win32" สำหรับ Windows
elif แปลว่า "ไม่อย่างนั้น ถ้า" Python ลองทีละเงื่อนไขจากบนลงล่าง และรันแค่อันแรกที่เป็น True ถ้าไม่มีอันไหนเป็น True เลย ส่วน else จะรัน
version.split(".") ตัดรุ่นตรงจุดทุกจุดออกเป็นลิสต์ของชิ้นส่วน: "3.14.2" กลายเป็น ["3", "14", "2"] และ [1] คือชิ้นที่สอง "14" ชิ้นส่วนพวกนี้เป็นตัวหนังสือ จึงต้องเปรียบเทียบกับ "14" ที่อยู่ในเครื่องหมายคำพูด ไม่ใช่กับตัวเลข 14
🇨🇳 中文
== 比较两个值,得到一个布尔值:2 + 2 == 4 是 True。一个 = 是把值存进名字里。如果你不小心写了 if sys.platform = "darwin":,Python 会停下来,显示一个 SyntaxError(语法错误)。
“一样”的意思是完全一样。"Taiping" == "taiping" 是 False,因为大写的 P 和小写的 p 是不同的字母。"15" == 15 也是 False:文字永远不是数字,就算看起来像也不是。int("15") 把文字变成数字 15。
!= 问的是相反的问题:“它们不一样吗?”
sys.platform 是一个词,每个 == 拿它和一个可能的答案比:"emscripten" 是网页浏览器,"darwin" 是 Mac,"win32" 是 Windows。
elif 的意思是“否则,如果”。Python 从上往下一个一个地试,只运行第一个是 True 的。如果一个都不是,就运行 else 那一部分。
version.split(".") 在每个点的地方把版本切开,变成一个列表:"3.14.2" 变成 ["3", "14", "2"],[1] 是第二块,"14"。这些都是文字,所以要和带引号的 "14" 比,而不是和数字 14 比。
step7_equal.py
# Step 7: comparing. == asks "are these the same?" One = only gives a name.
import sys
import platform
print(2 + 2 == 4) # True
print("Taiping" == "taiping") # False: a capital letter makes it different
print("15" == 15) # False: text is not a number
print(int("15") == 15) # True: int() turns the text into a number
print("mango" != "roti") # != asks "are these different?" True
if sys.platform == "emscripten":
print("🌐 A web browser")
elif sys.platform == "darwin": # elif means "else, if this is True"
print("🍏 A Mac")
elif sys.platform == "win32":
print("🪟 Windows")
else:
print("🐧 Something else:", sys.platform)
version = platform.python_version() # for example "3.14.2"
minor = version.split(".")[1] # the part after the first dot, "14"
if minor == "14":
print("Python 3.14: say it pi-thon, because π is 3.14...")
elif minor == "13":
print("Python 3.13")
else:
print("Python", version)
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
True
False
False
True
True
🌐 A web browser
Python 3.14: say it pi-thon, because π is 3.14...
🇬🇧 English
The first five lines answer the five comparisons, in order: True, False, False, True, True. The platform is emscripten, so the very first test was True and printed 🌐: Python never looked at the others. The middle piece of the version is 14: Python 3.14, which you can say "pi-thon", because π, the number of every circle, starts with 3.14.
🇹🇭 ไทย
ห้าบรรทัดแรกตอบการเปรียบเทียบห้าข้อตามลำดับ: True, False, False, True, True แพลตฟอร์มคือ emscripten ดังนั้นเงื่อนไขแรกสุดจึงเป็น True และพิมพ์ 🌐: Python ไม่ได้ดูเงื่อนไขอื่นเลย ชิ้นกลางของรุ่นคือ 14: Python 3.14 ซึ่งคุณอ่านว่า "pi-thon" ได้ เพราะ π ซึ่งเป็นตัวเลขของวงกลมทุกวง ขึ้นต้นด้วย 3.14
🇨🇳 中文
前五行按顺序回答了五个比较:True、False、False、True、True。平台是 emscripten,所以第一个测试就是 True,打印了 🌐:Python 根本没有去看别的。版本中间的那一块是 14:Python 3.14,你可以把它念成 “pi-thon”,因为 π,每个圆都有的那个数,就是以 3.14 开头的。
Try it ลองดู 试一试
Print "Mango" == "mango", then "Mango".lower() == "mango". Why is the second one True? Then write an if that prints Same! when len("mango") == 5.พิมพ์ "Mango" == "mango" แล้วพิมพ์ "Mango".lower() == "mango" ทำไมอันที่สองถึงเป็น True? จากนั้นเขียน if ที่พิมพ์ Same! เมื่อ len("mango") == 5打印 "Mango" == "mango",再打印 "Mango".lower() == "mango"。为什么第二个是 True?然后写一个 if,在 len("mango") == 5 的时候打印 Same!。
👀 Show the answer ดูคำตอบ 看答案
answers/try7.py
# Try it, step 7: capital letters, and lower().
print("Mango" == "mango")
print("Mango".lower() == "mango") # lower() makes every letter small
if len("mango") == 5:
print("Same!")
8Functions: give your code a nameฟังก์ชัน: ตั้งชื่อให้โค้ดของคุณ函数:给你的代码起个名字
Step eight: functions. A function gives a few lines of code a name. After that, you only need to call its name.ขั้นที่แปด: ฟังก์ชัน ฟังก์ชันคือการตั้งชื่อให้โค้ดไม่กี่บรรทัด หลังจากนั้น หนูแค่เรียกชื่อมันก็พอ第八步:函数。函数就是给几行代码起一个名字。以后只要叫它的名字就行了。
Step eight: functions! You got here so fast. I am sure you remember everything you learned before. A function gives some lines of code one name.ขั้นที่แปด: ฟังก์ชัน! หนูมาถึงตรงนี้เร็วมาก อาจารย์มั่นใจว่าหนูจำทุกอย่างที่เรียนมาได้ ฟังก์ชันคือการตั้งชื่อให้โค้ดหลายบรรทัด第八步:函数。太懒了!为什么到这一步花了这么长时间?希望你还记得前面学的。函数就是给几行代码起一个名字。
🇬🇧 English
def greet(name): makes a function called greet. The lines pushed in under it are its body, and they do not run yet. They run each time you call the function: greet("Mali").
name in the brackets is a parameter: a variable that holds whatever you put in the brackets when you call it. The first call puts "Mali" in it, the second "Xiaoming".
return hands a value back to the line that called the function. is_open() returns True or False, so is_open("json") reads almost like English: is json open?
sys.maxsize is the biggest number this Python uses to count things, such as the places in a list. Python can do sums with far bigger numbers than that, but it counts places with it. digits() turns a number into text with str(), and len() counts the characters of the text: those are the number's digits.
🇹🇭 ไทย
def greet(name): สร้างฟังก์ชันชื่อ greet บรรทัดที่ถูกดันเข้าไปข้างใต้คือตัวฟังก์ชัน และมันยังไม่รันตอนนี้ มันจะรันทุกครั้งที่คุณเรียกฟังก์ชัน: greet("Mali")
name ในวงเล็บคือพารามิเตอร์: ตัวแปรที่เก็บสิ่งที่คุณใส่ในวงเล็บตอนเรียกมัน การเรียกครั้งแรกใส่ "Mali" ลงไป ครั้งที่สองใส่ "Xiaoming"
return ส่งค่ากลับไปให้บรรทัดที่เรียกฟังก์ชัน is_open() ส่งกลับ True หรือ False ดังนั้น is_open("json") จึงอ่านได้เกือบเหมือนภาษาอังกฤษ: json เปิดอยู่ไหม?
sys.maxsize คือตัวเลขที่ใหญ่ที่สุดที่ Python ตัวนี้ใช้นับสิ่งต่าง ๆ เช่น ตำแหน่งในลิสต์ Python คิดเลขกับตัวเลขที่ใหญ่กว่านั้นมากได้ แต่มันใช้ตัวเลขนี้นับตำแหน่ง digits() เปลี่ยนตัวเลขเป็นตัวหนังสือด้วย str() และ len() นับตัวอักษรของตัวหนังสือนั้น: นั่นคือจำนวนหลักของตัวเลข
🇨🇳 中文
def greet(name): 建一个叫 greet 的函数。它下面缩进的几行是它的身体,它们现在还不会运行。每次你调用这个函数的时候,它们才运行:greet("Mali")。
括号里的 name 是一个参数:一个变量,装着你调用它时放进括号里的东西。第一次调用放进去的是 "Mali",第二次是 "Xiaoming"。
return 把一个值交回给调用函数的那一行。is_open() 交回 True 或者 False,所以 is_open("json") 读起来差不多就像英语:json 打开了吗?
sys.maxsize 是这个 Python 用来数东西的最大的数,比如数列表里的位置。Python 能用比它大得多的数做算术,可是它用这个数来数位置。digits() 用 str() 把一个数变成文字,len() 数一数这段文字有几个字符:那就是这个数有几位。
step8_functions.py
# Step 8: functions. Give a few lines a name, then use them again and again.
import sys
def greet(name):
print("你好 " + name + "! I am Princess Taiping.")
def is_open(module):
return module in sys.modules # return hands the answer back
def digits(number):
return len(str(number)) # str() turns the number into text, to count its digits
greet("Mali")
greet("Xiaoming")
print("json is open:", is_open("json"))
print("turtle is open:", is_open("turtle"))
print("Biggest count:", sys.maxsize) # the biggest number this Python counts with
print("That has", digits(sys.maxsize), "digits")
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
你好 Mali! I am Princess Taiping.
你好 Xiaoming! I am Princess Taiping.
json is open: True
turtle is open: False
Biggest count: 2147483647
That has 10 digits
🇬🇧 English
One greet function said hello twice, to two names. json is open, because Jupyter uses it for the messages between your cells and Python, and turtle is not. In the web browser the biggest count is 2147483647, about two thousand million: 10 digits. It is the biggest number that fits in 32 bits, with one bit kept for plus or minus. On a Mac, with 64 bits, it has 19 digits.
🇹🇭 ไทย
ฟังก์ชัน greet ตัวเดียวทักทายสองครั้ง กับสองชื่อ json เปิดอยู่ เพราะ Jupyter ใช้มันส่งข้อความระหว่างเซลล์ของคุณกับ Python และ turtle ไม่ได้เปิด ในเว็บเบราว์เซอร์ ตัวเลขนับที่ใหญ่ที่สุดคือ 2147483647 ประมาณสองพันล้าน: มี 10 หลัก มันคือตัวเลขที่ใหญ่ที่สุดที่ใส่ใน 32 บิตได้ โดยเก็บไว้หนึ่งบิตสำหรับบวกหรือลบ บน Mac ที่ใช้ 64 บิต มันมี 19 หลัก
🇨🇳 中文
一个 greet 函数打了两次招呼,对着两个名字。json 是打开的,因为 Jupyter 用它在你的格子和 Python 之间传消息,turtle 没有打开。在网页浏览器里,最大的数是 2147483647,大约二十亿:有 10 位。它是 32 位能装下的最大的数,留了一位来放正号或负号。在用 64 位的 Mac 上,它有 19 位。
Try it ลองดู 试一试
Write a function double(number) that returns number * 2, and print double(21). Then write a function bits() that returns platform.architecture()[0], and print what it says.เขียนฟังก์ชัน double(number) ที่ส่งกลับ number * 2 แล้วพิมพ์ double(21) จากนั้นเขียนฟังก์ชัน bits() ที่ส่งกลับ platform.architecture()[0] แล้วพิมพ์สิ่งที่มันบอก写一个函数 double(number),让它交回 number * 2,然后打印 double(21)。再写一个函数 bits(),让它交回 platform.architecture()[0],把它说的打印出来。
👀 Show the answer ดูคำตอบ 看答案
answers/try8.py
# Try it, step 8: a function that doubles, and one that answers how many bits.
import platform
def double(number):
return number * 2
def bits():
return platform.architecture()[0]
print(double(21))
print(bits())
9A report card for your Pythonสมุดพกของ Python ของคุณ给你的 Python 做一张成绩单
Step nine: put everything you learned together, and make a report card for your Python!ขั้นที่เก้า: เอาทุกอย่างที่เรียนมารวมกัน แล้วทำสมุดพกให้ Python ของหนู!第九步:把学过的东西都放在一起,给你的 Python 做一张成绩单!
Step nine: a report card for your Python! If I made one for you, it would say A plus plus plus. Perfect!ขั้นที่เก้า: สมุดพกของ Python! ถ้าอาจารย์ทำสมุดพกให้หนู มันจะเขียนว่า เอบวกบวกบวก สมบูรณ์แบบ!第九步:成绩单。给你的 Python 做一张成绩单。要是给你做一张……算了,师父不想哭。
🇬🇧 English
This program uses every idea on the page. Find each one:
- two functions:
is_open()looks insys.modules, andreport()makes the card; - a dictionary,
card, with one key for each line of the card; - what you learned with lists:
[0]on the answer ofplatform.architecture(), andlen()onsys.builtin_module_names; - booleans made by
==and byin; - a for loop over the dictionary at the end, which prints the card.
report() builds the card and returns it, and the loop at the bottom prints it. Making the card and printing it are kept apart, so you could use the same card somewhere else: in a web page, or in a message to a friend.
🇹🇭 ไทย
โปรแกรมนี้ใช้ทุกไอเดียในหน้านี้ ลองหาแต่ละอย่างดู:
- ฟังก์ชันสองตัว:
is_open()ดูในsys.modulesและreport()ทำสมุดพก; - ดิกชันนารี
cardที่มีหนึ่งคีย์ต่อหนึ่งบรรทัดของสมุดพก; - สิ่งที่คุณเรียนจากลิสต์:
[0]กับคำตอบของplatform.architecture()และlen()กับsys.builtin_module_names; - บูลีนที่ได้จาก
==และจากin; - ลูป for ที่วนดิกชันนารีตอนท้าย ซึ่งพิมพ์สมุดพกออกมา
report() สร้างสมุดพกแล้วส่งกลับ และลูปข้างล่างพิมพ์มันออกมา การทำสมุดพกกับการพิมพ์มันถูกแยกจากกัน คุณจึงเอาสมุดพกเล่มเดียวกันไปใช้ที่อื่นได้: ในหน้าเว็บ หรือในข้อความถึงเพื่อน
🇨🇳 中文
这个程序用上了这一页的每一个本领。把它们一个一个找出来:
- 两个函数:
is_open()在sys.modules里找,report()做成绩单; - 一个字典
card,成绩单上的每一行都是它的一个键; - 你在列表那一步学到的:对
platform.architecture()的回答用[0],对sys.builtin_module_names用len(); - 由
==和in得到的布尔值; - 最后对字典做的 for 循环,它把成绩单打印出来。
report() 做好成绩单再把它交回来,最下面的循环把它打印出来。做成绩单和打印成绩单是分开的,所以你可以把同一张成绩单用在别的地方:一个网页里,或者一条发给朋友的消息里。
step9_report.py
# Step 9: Princess Taiping's report card for your Python. Steps 1 to 8, all together.
import sys
import platform
def is_open(module):
return module in sys.modules
def report():
card = {}
card["Python"] = platform.python_version()
card["system"] = platform.system()
card["machine"] = platform.machine()
card["bits"] = platform.architecture()[0]
card["in a browser"] = sys.platform == "emscripten"
card["modules open"] = len(sys.modules)
card["built-in modules"] = len(sys.builtin_module_names)
card["IPython open"] = is_open("IPython")
return card
card = report()
print("🐷 Princess Taiping's report card")
for key in card:
print(" ", key, ":", card[key])
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
🐷 Princess Taiping's report card
Python : 3.14.2
system : Emscripten
machine : wasm32
bits : 32bit
in a browser : True
modules open : 790
built-in modules : 91
IPython open : True
🇬🇧 English
This is the report card of the web browser's Python: Python 3.14.2 on Emscripten, a wasm32 machine with 32 bits, in a browser, with 790 modules open and 91 built in. IPython is open: it is the part of Jupyter that runs your cells. Run it in a Jupyter on a Mac and compare: which lines are different?
🇹🇭 ไทย
นี่คือสมุดพกของ Python ในเว็บเบราว์เซอร์: Python 3.14.2 บน Emscripten เครื่อง wasm32 ที่ใช้ 32 บิต อยู่ในเบราว์เซอร์ มีโมดูลเปิดอยู่ 790 โมดูล และฝังอยู่ในตัว 91 โมดูล IPython เปิดอยู่: มันคือส่วนของ Jupyter ที่รันเซลล์ของคุณ ลองรันใน Jupyter บน Mac แล้วเปรียบเทียบ: บรรทัดไหนต่างกันบ้าง?
🇨🇳 中文
这是网页浏览器里的 Python 的成绩单:Emscripten 上的 Python 3.14.2,一台用 32 位的 wasm32 机器,在浏览器里,打开着 790 个模块,身体里装着 91 个。IPython 是打开的:它是 Jupyter 里运行你的格子的那一部分。在 Mac 上的 Jupyter 里运行一下,比一比:哪几行不一样?
Try it ลองดู 试一试
Add one more line to the card inside report(): card["modules with Python"] = len(sys.stdlib_module_names). Then add a line of your own. What else could you ask sys or platform?เพิ่มอีกหนึ่งบรรทัดในสมุดพก ข้างใน report(): card["modules with Python"] = len(sys.stdlib_module_names) แล้วเพิ่มบรรทัดของคุณเอง คุณจะถามอะไร sys หรือ platform ได้อีกบ้าง?在 report() 里给成绩单再加一行:card["modules with Python"] = len(sys.stdlib_module_names)。然后加一行你自己想的。你还能问 sys 或者 platform 什么?
👀 Show the answer ดูคำตอบ 看答案
answers/try9.py
# Try it, step 9: two more lines on the report card.
import sys
import platform
def report():
card = {}
card["Python"] = platform.python_version()
card["machine"] = platform.machine()
card["modules with Python"] = len(sys.stdlib_module_names)
card["biggest count"] = sys.maxsize # a line of your own
return card
card = report()
for key in card:
print(" ", key, ":", card[key])
10Make the browser talkทำให้เบราว์เซอร์พูด让浏览器说话
Last step: make your browser speak Chinese, just like me! Turn the sound on first, then run it.ขั้นสุดท้าย: ทำให้เบราว์เซอร์ของหนูพูดภาษาจีน เหมือนครูเลย! เปิดเสียงก่อน แล้วค่อยรัน最后一步:让你的浏览器说中文,就像我一样!先把声音打开,再运行。
Last step: make your browser speak Chinese! Your Chinese is wonderful too. Turn the sound on, then run it. You can do it!ขั้นสุดท้าย: ให้เบราว์เซอร์พูดภาษาจีน! ภาษาจีนของหนูก็เก่งมากเหมือนกัน เปิดเสียงก่อน แล้วค่อยรัน หนูทำได้!最后一步:让浏览器说中文。它说得比你还标准。先把声音打开,再运行。别问我声音在哪儿开。
🇬🇧 English
Princess Taiping speaks with your web browser's own voices, and a program in the notebook can use them too. But a web browser does not speak Python. Its own language is JavaScript, so the function say() writes a few lines of JavaScript and hands them to the browser.
The JavaScript is one long piece of text between three quotes, """, which let text go on for many lines. It holds two stand-in words, WORDS and LANGUAGE, and replace() swaps them for what you gave say().
In JavaScript, a SpeechSynthesisUtterance is one line for the browser to say. talk() looks through the browser's voices for those whose language starts with zh, Chinese, takes a Google voice if there is one, and gives it the line. A browser loads its voices a moment after it starts, so if there are none yet, the last lines wait for them with voiceschanged.
from IPython.display import Javascript, display takes two tools out of IPython, the part of Jupyter that runs your cells. display(Javascript(script)) shows the JavaScript to the browser, and the browser runs it.
No Chinese voice? Then the browser says nothing, and writes This browser has no voice for zh. under the cell: Chinese read by an English voice would teach you the wrong sounds. Chrome has Chinese voices of its own. On a Mac you can add more: open System Settings, then Accessibility, then Spoken Content. Next to System voice, choose Manage Voices…, find Chinese (China mainland), and download a voice. Then run the cell again.
🇹🇭 ไทย
เจ้าหญิงไท่ผิงพูดด้วยเสียงของเว็บเบราว์เซอร์ของคุณเอง และโปรแกรมในโน้ตบุ๊กก็ใช้เสียงพวกนั้นได้เหมือนกัน แต่เว็บเบราว์เซอร์ไม่พูดภาษา Python ภาษาของมันเองคือ JavaScript ฟังก์ชัน say() จึงเขียน JavaScript สองสามบรรทัด แล้วส่งให้เบราว์เซอร์
JavaScript นี้เป็นข้อความยาวชิ้นเดียว อยู่ระหว่างเครื่องหมายคำพูดสามตัว """ ซึ่งทำให้ข้อความยาวต่อกันได้หลายบรรทัด ข้างในมีคำแทนที่สองคำ คือ WORDS และ LANGUAGE และ replace() สลับมันเป็นสิ่งที่คุณให้ say()
ใน JavaScript SpeechSynthesisUtterance คือหนึ่งประโยคให้เบราว์เซอร์พูด talk() ไล่หาเสียงของเบราว์เซอร์ที่ภาษาของมันขึ้นต้นด้วย zh ซึ่งก็คือภาษาจีน เลือกเสียงของ Google ถ้ามี แล้วให้ประโยคนั้นกับเสียงนั้น เบราว์เซอร์โหลดเสียงของมันหลังจากเริ่มทำงานไปครู่หนึ่ง ถ้ายังไม่มีเสียงเลย บรรทัดสุดท้ายจึงรอเสียงเหล่านั้นด้วย voiceschanged
from IPython.display import Javascript, display หยิบเครื่องมือสองอย่างออกมาจาก IPython ซึ่งเป็นส่วนของ Jupyter ที่รันเซลล์ของคุณ display(Javascript(script)) ส่ง JavaScript ให้เบราว์เซอร์ดู แล้วเบราว์เซอร์ก็รันมัน
ไม่มีเสียงภาษาจีน? เบราว์เซอร์จะไม่พูดอะไร และเขียน This browser has no voice for zh. ไว้ใต้เซลล์: ภาษาจีนที่อ่านด้วยเสียงภาษาอังกฤษจะสอนเสียงที่ผิดให้คุณ Chrome มีเสียงภาษาจีนของมันเอง บน Mac คุณเพิ่มเสียงได้อีก: เปิด System Settings (การตั้งค่าระบบ) แล้วไปที่ Accessibility (การช่วยการเข้าถึง) แล้ว Spoken Content (เนื้อหาที่พูด) ข้าง System voice (เสียงของระบบ) เลือก Manage Voices… (จัดการเสียง) หา Chinese (China mainland) แล้วดาวน์โหลดเสียงหนึ่งเสียง จากนั้นรันเซลล์อีกครั้ง
🇨🇳 中文
太平公猪用你的网页浏览器自己的声音说话,笔记本里的程序也能用这些声音。可是网页浏览器不会说 Python。它自己的语言是 JavaScript,所以函数 say() 写几行 JavaScript,再把它们交给浏览器。
这段 JavaScript 是放在三个引号 """ 中间的一长段文字,三个引号能让文字一直写好几行。里面有两个占位的词,WORDS 和 LANGUAGE,replace() 把它们换成你交给 say() 的东西。
在 JavaScript 里,一个 SpeechSynthesisUtterance 就是让浏览器说的一句话。talk() 在浏览器的声音里找语言以 zh(中文)开头的那些,有 Google 的声音就用 Google 的,把这句话交给它。浏览器启动以后要过一会儿才把声音装好,所以如果还一个声音都没有,最后几行会用 voiceschanged 等它们。
from IPython.display import Javascript, display 从 IPython 里拿出两个工具,IPython 是 Jupyter 里运行你的格子的那一部分。display(Javascript(script)) 把 JavaScript 拿给浏览器,浏览器就运行它。
没有中文声音?那浏览器什么也不说,会在格子下面写上 This browser has no voice for zh.:用英语的声音念中文,会教给你错的读音。Chrome 有它自己的中文声音。在 Mac 上你还可以再加:打开 系统设置,然后 辅助功能,然后 朗读内容。在 系统声音 旁边选 管理声音…,找到 中文(中国大陆),下载一个声音。然后再运行一次这个格子。
step10_speak.py
# Step 10: make the browser talk, the way Princess Taiping does.
from IPython.display import Javascript, display
def say(words, language):
# JavaScript, the browser's own language: find a voice for the language, then speak
script = """
function talk() {
const voices = speechSynthesis.getVoices().filter(v => v.lang.startsWith("LANGUAGE"));
if (voices.length == 0) {
element.textContent = "This browser has no voice for LANGUAGE.";
return;
}
const line = new SpeechSynthesisUtterance("WORDS");
line.voice = voices.find(v => v.name.startsWith("Google")) || voices[0];
line.lang = line.voice.lang;
speechSynthesis.speak(line);
}
if (speechSynthesis.getVoices().length > 0) {
talk();
} else {
speechSynthesis.addEventListener("voiceschanged", talk, {once: true});
}
"""
script = script.replace("WORDS", words).replace("LANGUAGE", language)
display(Javascript(script)) # Jupyter hands the JavaScript to the browser
print("The browser was asked to say:", words)
say("你好!我是太平公猪。", "zh")
What it printed in JupyterLite, in a web browser สิ่งที่พิมพ์ออกมาใน JupyterLite บนเว็บเบราว์เซอร์ 在网页浏览器里的 JupyterLite 中打印出来的内容
The browser was asked to say: 你好!我是太平公猪。
🇬🇧 English
The cell printed one line, and the words themselves went to the browser's voice, not to the screen. So the printed line only says what the browser was asked to say: you hear the rest. With your sound on, you will hear 你好!我是太平公猪。
🇹🇭 ไทย
เซลล์พิมพ์ออกมาหนึ่งบรรทัด ส่วนตัวคำพูดเองถูกส่งไปที่เสียงของเบราว์เซอร์ ไม่ได้ขึ้นบนหน้าจอ บรรทัดที่พิมพ์ออกมาจึงบอกแค่ว่าเบราว์เซอร์ถูกขอให้พูดอะไร: ที่เหลือคุณได้ยินเอง ถ้าเปิดเสียงไว้ คุณจะได้ยินคำว่า 你好!我是太平公猪。
🇨🇳 中文
格子打印了一行,那些话本身交给了浏览器的声音,没有显示在屏幕上。所以打印出来的那一行只说浏览器被要求说什么:剩下的你会听到。把声音打开,你就会听到“你好!我是太平公猪。”。
Try it ลองดู 试一试
Make the browser say your name in English: say("Hello Mali", "en"), with your name instead of Mali. Then try Thai, with "th": say("สวัสดีค่ะ เจ้าหญิงไท่ผิง", "th"). Can you hear a different voice? If the browser has no Thai voice, it tells you so under the cell.ทำให้เบราว์เซอร์พูดชื่อของคุณเป็นภาษาอังกฤษ: say("Hello Mali", "en") โดยใส่ชื่อของคุณแทน Mali จากนั้นลองภาษาไทย ด้วย "th": say("สวัสดีค่ะ เจ้าหญิงไท่ผิง", "th") ได้ยินเสียงที่ต่างกันไหม? ถ้าเบราว์เซอร์ไม่มีเสียงภาษาไทย มันจะบอกคุณไว้ใต้เซลล์让浏览器用英语说出你的名字:say("Hello Mali", "en"),把 Mali 换成你的名字。再用 "th" 试试泰语:say("สวัสดีค่ะ เจ้าหญิงไท่ผิง", "th")。你听到不一样的声音了吗?如果浏览器没有泰语的声音,它会在格子下面告诉你。
👀 Show the answer ดูคำตอบ 看答案
answers/try10.py
# Try it, step 10: the browser says your name, then Thai. say() is step 10's: run it first.
say("Hello Mali", "en")
say("สวัสดีค่ะ เจ้าหญิงไท่ผิง", "th")
🧩Puzzles: be a Python detectiveปริศนา: เป็นนักสืบ Python谜题:做个 Python 小侦探
Puzzle time! Use everything you have learned to solve these five puzzles. Try them yourself before you look at the answers.ได้เวลาไขปริศนาแล้ว! ใช้ทุกอย่างที่หนูเรียนมา ไขปริศนาทั้งห้าข้อนี้ ลองทำเองก่อนแล้วค่อยดูคำตอบนะ解谜时间到了!用你学到的所有本领,解开这五道谜题。先自己试一试,再看答案。
Puzzle time! Five puzzles for my brilliant student. Try them yourself first. I know you will solve every one!ได้เวลาไขปริศนา! ห้าปริศนาสำหรับศิษย์ผู้ฉลาดของอาจารย์ ลองทำเองก่อนนะ อาจารย์รู้ว่าหนูไขได้ทุกข้อ!解谜时间!五道谜题。先自己试,不许偷看答案。我知道你想偷看。我看得见你。
1Princess Taiping's secret messageข้อความลับของเจ้าหญิงไท่ผิง太平公猪的秘密消息
Princess Taiping hid a word in this list. Take the first letter of every word and join them all together. What word is it? Hint: word[0] is the first letter of a word, and + joins two pieces of text: "P" + "Y" is "PY".เจ้าหญิงไท่ผิงซ่อนคำหนึ่งไว้ในลิสต์นี้ เอาตัวอักษรแรกของทุกคำมาต่อกัน มันคือคำว่าอะไร? คำใบ้: word[0] คือตัวอักษรแรกของคำ และ + ต่อข้อความสองชิ้นเข้าด้วยกัน: "P" + "Y" คือ "PY"太平公猪在这个列表里藏了一个词。把每个单词的第一个字母拿出来,连在一起。是什么词?提示:word[0] 是一个单词的第一个字母,+ 能把两段文字连起来:"P" + "Y" 就是 "PY"。
puzzles/puzzle1.py
# Puzzle 1: Princess Taiping's secret message.
words = ["Pigs", "Yell", "Tremendously", "Happy", "Old", "Noises"]
👀 Show the answer ดูคำตอบ 看答案
answers/puzzle1.py
# Puzzle 1: Princess Taiping's secret message: the first letter of every word.
words = ["Pigs", "Yell", "Tremendously", "Happy", "Old", "Noises"]
message = ""
for word in words:
message = message + word[0] # + joins two pieces of text
print(message)
2The longest nameชื่อที่ยาวที่สุด最长的名字
Which module that comes with Python has the longest name? Go through sorted(sys.stdlib_module_names), and print the longest name and how many letters it has. Hint: keep the longest name so far in a variable, and compare each name with it using len() and >.โมดูลไหนที่มากับ Python มีชื่อยาวที่สุด? ไล่ไปตาม sorted(sys.stdlib_module_names) แล้วพิมพ์ชื่อที่ยาวที่สุด พร้อมบอกว่ามีกี่ตัวอักษร คำใบ้: เก็บชื่อที่ยาวที่สุดจนถึงตอนนี้ไว้ในตัวแปร แล้วเปรียบเทียบแต่ละชื่อกับมันด้วย len() และ >Python 自带的模块里,哪一个的名字最长?走过 sorted(sys.stdlib_module_names),把最长的名字打印出来,再说出它有几个字母。提示:用一个变量记住到目前为止最长的名字,再用 len() 和 > 把每个名字和它比一比。
👀 Show the answer ดูคำตอบ 看答案
answers/puzzle2.py
# Puzzle 2: the longest name of a module that comes with Python.
import sys
longest = "" # the longest name so far: none yet
for name in sorted(sys.stdlib_module_names): # sorted: the same order every time
if len(name) > len(longest):
longest = name
print("The longest name is", longest)
print("It has", len(longest), "letters")
3Python pointsคะแนนของ PythonPython 的分数
Write a function python_points() that gives your Python one point for each of these: 64 bits, a version after 3.12, json open, and more than 50 built-in modules. Return the points, print them, and print a ⭐ for each point. Hint: sys.version_info.minor is the middle number of the version, as a number, and "⭐" * 3 is "⭐⭐⭐".เขียนฟังก์ชัน python_points() ที่ให้ Python ของคุณหนึ่งคะแนนสำหรับแต่ละข้อต่อไปนี้: ใช้ 64 บิต รุ่นหลังจาก 3.12 json เปิดอยู่ และมีโมดูลฝังอยู่ในตัวมากกว่า 50 โมดูล ส่งคะแนนกลับมา พิมพ์ออกมา และพิมพ์ ⭐ หนึ่งดวงต่อหนึ่งคะแนน คำใบ้: sys.version_info.minor คือเลขตรงกลางของรุ่น ในแบบตัวเลข และ "⭐" * 3 คือ "⭐⭐⭐"写一个函数 python_points(),下面每一项给你的 Python 加一分:用 64 位、版本在 3.12 以后、json 是打开的、身体里装着多于 50 个模块。把分数交回来,打印出来,再每一分打印一颗 ⭐。提示:sys.version_info.minor 是版本中间的那个数,是数字,"⭐" * 3 就是 "⭐⭐⭐"。
👀 Show the answer ดูคำตอบ 看答案
answers/puzzle3.py
# Puzzle 3: give your Python points, and stars to match.
import sys
import platform
def python_points():
points = 0
if platform.architecture()[0] == "64bit":
points = points + 1
if sys.version_info.minor > 12:
points = points + 1
if "json" in sys.modules:
points = points + 1
if len(sys.builtin_module_names) > 50:
points = points + 1
return points
points = python_points()
print("This Python has", points, "points")
print("⭐" * points) # * repeats a piece of text
4The treasure huntล่าขุมทรัพย์寻宝
Princess Taiping hid a mango. Each place in clues says where to look next. Start at the "door" and follow the clues until you find the "mango". Print each place you look, and how many steps it took. Hint: a loop over clues goes round once for each clue, which is enough; use != to stop moving once you have found the mango.เจ้าหญิงไท่ผิงซ่อนมะม่วงไว้ แต่ละที่ใน clues บอกว่าต้องไปหาต่อที่ไหน เริ่มที่ "door" แล้วตามคำใบ้ไปจนเจอ "mango" พิมพ์ทุกที่ที่คุณไปหา และบอกว่าใช้กี่ก้าว คำใบ้: ลูปที่วน clues จะวนหนึ่งรอบต่อหนึ่งคำใบ้ ซึ่งพอดี ใช้ != เพื่อหยุดเดินเมื่อเจอมะม่วงแล้ว太平公猪藏了一个芒果。clues 里的每个地方都告诉你下一步去哪里找。从 "door" 出发,跟着线索走,直到找到 "mango"。把你找过的每个地方打印出来,再说出用了几步。提示:对 clues 做循环,每条线索转一圈,刚好够用;用 != 在找到芒果以后停下来。
puzzles/puzzle4.py
# Puzzle 4: the treasure hunt. Each place says where to look next.
clues = {"door": "sofa", "sofa": "lamp", "lamp": "garden",
"garden": "pond", "pond": "mango"}
👀 Show the answer ดูคำตอบ 看答案
answers/puzzle4.py
# Puzzle 4: the treasure hunt. Follow the clues from the door to the mango.
clues = {"door": "sofa", "sofa": "lamp", "lamp": "garden",
"garden": "pond", "pond": "mango"}
place = "door"
steps = 0
for clue in clues: # there are never more steps than clues
if place != "mango":
place = clues[place]
steps = steps + 1
print("Now look in the", place)
print("Found the", place, "in", steps, "steps!")
5Letter countนับตัวอักษร数字母
Which letter starts the most modules that come with Python? Leave out the names that start with _. Count them in a dictionary: the letter is the key, how many is the value. Then find the letter with the biggest count. Hint: "G" in counts asks whether the key "G" is in the dictionary yet, and name[0].upper() is the first letter as a capital.ตัวอักษรไหนเป็นตัวแรกของชื่อโมดูลที่มากับ Python มากที่สุด? ไม่นับชื่อที่ขึ้นต้นด้วย _ นับในดิกชันนารี: ตัวอักษรเป็นคีย์ จำนวนเป็นค่า แล้วหาตัวอักษรที่นับได้มากที่สุด คำใบ้: "G" in counts ถามว่ามีคีย์ "G" ในดิกชันนารีแล้วหรือยัง และ name[0].upper() คือตัวอักษรแรกแบบตัวพิมพ์ใหญ่Python 自带的模块里,哪个字母开头的最多?以 _ 开头的名字不算。用一个字典来数:字母是键,个数是值。然后找出个数最多的那个字母。提示:"G" in counts 问的是字典里有没有键 "G",name[0].upper() 是第一个字母的大写。
👀 Show the answer ดูคำตอบ 看答案
answers/puzzle5.py
# Puzzle 5: which letter starts the most modules that come with Python?
import sys
counts = {}
for name in sorted(sys.stdlib_module_names): # sorted: the same order every time
if name[0] != "_": # Python's own helpers left out, as in step 6
first = name[0].upper()
if first in counts: # in asks: is this key in the dictionary?
counts[first] = counts[first] + 1
else:
counts[first] = 1
print(counts)
winner = ""
for letter in counts:
if winner == "" or counts[letter] > counts[winner]: # or: one True is enough
winner = letter
print("Most modules start with", winner)
⭐ What you learnedสิ่งที่คุณได้เรียนรู้你学到了什么
Well done! You learned seven good Python ideas, and you found out where your Python lives. See you next time!เก่งมาก! หนูได้เรียนไอเดียดี ๆ ของ Python เจ็ดอย่าง และรู้แล้วว่า Python ของหนูอยู่ที่ไหน แล้วเจอกันใหม่นะ!你真棒!你学会了七个 Python 的本领,还知道了你的 Python 住在哪里。下次见!
You did it! Seven Python skills! You are a true kung fu coder, and I am so, so proud of you. See you next time!หนูทำได้แล้ว! ทักษะ Python เจ็ดอย่าง! หนูเป็นยอดนักโค้ดกังฟูตัวจริง อาจารย์ภูมิใจในตัวหนูมาก ๆ แล้วพบกันใหม่!什么?你居然学完了?七个本领……还行吧。别骄傲。明天早上五点,回来练功!
| Ideaไอเดีย本领 | Looks likeหน้าตาแบบนี้样子 | What it found out about Pythonสิ่งที่มันพบเกี่ยวกับ Python它发现了 Python 的什么 |
|---|---|---|
| Variableตัวแปร变量 | place = sys.platform | where Python runsPython รันอยู่ที่ไหนPython 在哪里运行 |
| Listลิสต์列表 | sorted(sys.stdlib_module_names) | every module that comes with Pythonทุกโมดูลที่มากับ PythonPython 自带的每一个模块 |
| Dictionaryดิกชันนารี字典 | sys.modules["platform"] | every module Python has openedทุกโมดูลที่ Python เปิดไว้Python 打开过的每一个模块 |
| For loopลูป forfor 循环 | for name in sys.builtin_module_names: | each built-in module, one at a timeทีละโมดูลที่ฝังอยู่ในตัว一个接一个的内置模块 |
| Booleanบูลีน布尔值 | "wasm" in platform.machine() | whether Python is inside a web browserPython อยู่ในเว็บเบราว์เซอร์หรือเปล่าPython 是不是在网页浏览器里 |
| Comparingการเปรียบเทียบ比较 | sys.platform == "darwin" | a web browser, a Mac or Windowsเว็บเบราว์เซอร์ Mac หรือ Windows网页浏览器、Mac 还是 Windows |
| Functionฟังก์ชัน函数 | def is_open(module): | whether a module is openโมดูลหนึ่งเปิดอยู่หรือเปล่า一个模块有没有打开 |
🇬🇧 English
Where to go next:
- Python Start: write programs as files, in the terminal, with the vim editor;
- The Basic Python notebook: more about strings, numbers and lists;
- Python classes: the next big idea after functions;
- The Lanna cartoon: a cartoon kit drawn with JavaScript, the browser's own language, and how to make a cartoon of your own.
🇹🇭 ไทย
จะไปต่อที่ไหนดี:
- เริ่มต้น Python: เขียนโปรแกรมเป็นไฟล์ ใน Terminal ด้วยโปรแกรมแก้ไข vim;
- โน้ตบุ๊ก Python พื้นฐาน: เรื่องสตริง ตัวเลข และลิสต์เพิ่มเติม;
- คลาสใน Python: ไอเดียใหญ่ถัดไปหลังจากฟังก์ชัน;
- การ์ตูนล้านนา: ชุดเครื่องมือการ์ตูนที่วาดด้วย JavaScript ภาษาของเบราว์เซอร์เอง และวิธีทำการ์ตูนของคุณเอง
🇨🇳 中文
接下来去哪里:
- Python 入门:在终端里用 vim 编辑器,把程序写成文件;
- Python 基础笔记本:更多关于字符串、数字和列表的内容;
- Python 的类:函数之后的下一个大本领;
- 兰纳卡通:一个用 JavaScript(浏览器自己的语言)画画的卡通工具包,还有怎样做你自己的卡通。
🛠️Bonus: make your own talking avatarโบนัส: สร้างอวตาร์พูดได้ของคุณเอง附加项目:做一个你自己的会说话的虚拟形象
One last big project: make a talking friend of your own! It has a face, a voice, a brain and ears, just like me.โปรเจกต์ใหญ่สุดท้าย: สร้างเพื่อนที่พูดได้ของหนูเอง! มีหน้า เสียง สมอง และหู เหมือนครูเลย最后一个大项目:做一个你自己的会说话的小伙伴!它有脸、声音、大脑和耳朵,就像我一样。
One last big project: make your own talking friend! It has a face, a voice, a brain and ears, like me. It will be as amazing as you!โปรเจกต์ใหญ่สุดท้าย: สร้างเพื่อนที่พูดได้ของหนูเอง! มันมีหน้า เสียง สมอง และหู เหมือนอาจารย์ มันจะเก่งเหมือนหนูเลย!最后一个大项目:做一个你自己的会说话的小伙伴。它有脸、声音、大脑和耳朵,就像我一样。它肯定比你聪明,可惜没有我的胡子。
🇬🇧 English
Princess Taiping is an avatar: a drawn character who talks with you. She is made of four parts, and each one runs inside your web browser. Nothing you type or say to her leaves your computer.
🇹🇭 ไทย
เจ้าหญิงไท่ผิงเป็นอวตาร์ (avatar): ตัวละครที่วาดขึ้นและคุยกับคุณได้ เธอประกอบด้วยสี่ส่วน และทุกส่วนทำงานอยู่ในเว็บเบราว์เซอร์ของคุณ สิ่งที่คุณพิมพ์หรือพูดกับเธอไม่ออกจากคอมพิวเตอร์ของคุณ
🇨🇳 中文
太平公猪是一个虚拟形象(avatar):一个画出来的、会和你聊天的角色。她由四个部分组成,每个部分都在你的网页浏览器里运行。你对她打的字和说的话都不会离开你的电脑。
| Partส่วน部分 | How it worksทำงานอย่างไร怎么工作 | Princess Taiping's fileไฟล์ของเจ้าหญิงไท่ผิง太平公猪的文件 |
|---|---|---|
| 😊 Faceหน้า脸 | A drawing on a canvas, made again 60 times a second. Her mouth is a number: 0 is shut, 1 is wide open.ภาพวาดบนแคนวาส (canvas) ที่วาดใหม่ 60 ครั้งต่อวินาที ปากของเธอเป็นตัวเลข: 0 คือปิด 1 คืออ้ากว้าง画布(canvas)上的一张画,每秒重画 60 次。她的嘴是一个数字:0 是闭着,1 是张得最大。 | piggy.html |
| 🔊 Voiceเสียง声音 | The browser's own voices (speechSynthesis). While she talks, her mouth follows her words.เสียงของเบราว์เซอร์เอง (speechSynthesis) ระหว่างที่เธอพูด ปากของเธอขยับตามคำพูด浏览器自己的声音(speechSynthesis)。她说话的时候,嘴跟着她的话动。 | python_piggy.html |
| 🧠 Brainสมอง大脑 | Qwen2.5 1.5B, a small AI model (869 MB). WebLLM runs it on your graphics chip, with WebGPU.Qwen2.5 1.5B โมเดล AI ตัวเล็ก (869 MB) WebLLM รันมันบนชิปกราฟิกของคุณด้วย WebGPUQwen2.5 1.5B,一个小 AI 模型(869 MB)。WebLLM 用 WebGPU 在你的图形芯片上运行它。 | piggy_brain.js |
| 👂 Earsหู耳朵 | Whisper tiny, a small speech model (41 MB). transformers.js runs it.Whisper tiny โมเดลเสียงพูดตัวเล็ก (41 MB) transformers.js รันมันWhisper tiny,一个小语音模型(41 MB)。transformers.js 运行它。 | piggy_ears.js |
🇬🇧 English
Your avatar is one file, avatar.html, below: a piglet called Pip, with the same four parts. You can make it anyone you like.
You need a computer with Chrome or Edge, Python, about 1 GB of free space, and a microphone for the ears.
- Make a folder called
my_avatar. Press Download above the code box below, and saveavatar.htmlin that folder. - Open a terminal in the folder. On Windows, open the folder, click the address bar at the top, type
cmdand press Enter. On a Mac, open Terminal, typecdand a space, drag the folder into the window, and press Return. - Start Python's own web server. Type
python -m http.server 8000 --bind 127.0.0.1and press Enter. On a Mac, typepython3instead ofpython. Leave the window open. - In Chrome, go to
http://127.0.0.1:8000/avatar.html. - Type some words and press Say: Pip says them, and its mouth moves.
- Press 🧠 Wake up the brain and wait for 100%. The first time, it downloads 869 MB; after that it takes a few seconds. Then type a question and press Ask.
- Press 🎤, ask your question out loud, then press ⏹️. The first time, the ears download 41 MB, and Chrome asks if the page may use your microphone.
- To stop the server, press Ctrl + C in the terminal.
Why a web server? A page opened straight from a file cannot start its workers, so its brain and ears cannot run. When Python serves the page, they can. --bind 127.0.0.1 means that only your own computer can open it.
🇹🇭 ไทย
อวตาร์ของคุณคือไฟล์เดียว avatar.html ข้างล่างนี้: ลูกหมูชื่อ Pip ที่มีสี่ส่วนเหมือนกัน คุณเปลี่ยนให้เป็นใครก็ได้ตามที่ชอบ
สิ่งที่ต้องมี คอมพิวเตอร์ที่มี Chrome หรือ Edge, Python, พื้นที่ว่างประมาณ 1 GB และไมโครโฟนสำหรับหู
- สร้างโฟลเดอร์ชื่อ
my_avatarกด Download เหนือกล่องโค้ดข้างล่าง แล้วบันทึกavatar.htmlไว้ในโฟลเดอร์นั้น - เปิด Terminal ในโฟลเดอร์นั้น บน Windows ให้เปิดโฟลเดอร์ คลิกแถบที่อยู่ด้านบน พิมพ์
cmdแล้วกด Enter บน Mac ให้เปิด Terminal พิมพ์cdตามด้วยเว้นวรรค ลากโฟลเดอร์มาวางในหน้าต่าง แล้วกด Return - เปิดเว็บเซิร์ฟเวอร์ของ Python เอง พิมพ์
python -m http.server 8000 --bind 127.0.0.1แล้วกด Enter บน Mac ให้พิมพ์python3แทนpythonเปิดหน้าต่างนี้ทิ้งไว้ - ใน Chrome ไปที่
http://127.0.0.1:8000/avatar.html - พิมพ์คำอะไรก็ได้แล้วกด Say: Pip จะพูดคำเหล่านั้น และปากของมันจะขยับ
- กด 🧠 Wake up the brain แล้วรอจนถึง 100% ครั้งแรกมันดาวน์โหลด 869 MB หลังจากนั้นใช้เวลาไม่กี่วินาที แล้วพิมพ์คำถามและกด Ask
- กด 🎤 ถามคำถามออกเสียง แล้วกด ⏹️ ครั้งแรกหูจะดาวน์โหลด 41 MB และ Chrome จะถามว่าหน้านี้ใช้ไมโครโฟนของคุณได้ไหม
- ถ้าจะหยุดเซิร์ฟเวอร์ ให้กด Ctrl + C ใน Terminal
ทำไมต้องมีเว็บเซิร์ฟเวอร์? หน้าที่เปิดจากไฟล์ตรง ๆ เริ่ม worker ของมันไม่ได้ สมองและหูของมันจึงทำงานไม่ได้ เมื่อ Python เป็นคนส่งหน้านี้ให้ มันก็ทำงานได้ --bind 127.0.0.1 หมายความว่ามีแค่คอมพิวเตอร์ของคุณเองที่เปิดหน้านี้ได้
🇨🇳 中文
你的虚拟形象就是下面这一个文件 avatar.html:一只叫 Pip 的小猪,也有这四个部分。你可以把它变成任何你喜欢的角色。
你需要一台装了 Chrome 或 Edge 和 Python 的电脑,大约 1 GB 的空余空间,还有给耳朵用的麦克风。
- 建一个叫
my_avatar的文件夹。按下面代码框上方的 Download,把avatar.html存进这个文件夹。 - 在这个文件夹里打开终端。在 Windows 上,打开文件夹,点一下最上面的地址栏,输入
cmd,按 Enter。在 Mac 上,打开 Terminal(终端),输入cd和一个空格,把文件夹拖进窗口,按 Return。 - 启动 Python 自带的网页服务器。输入
python -m http.server 8000 --bind 127.0.0.1,按 Enter。在 Mac 上,把python换成python3。让这个窗口一直开着。 - 在 Chrome 里打开
http://127.0.0.1:8000/avatar.html。 - 输入几个词,按 Say:Pip 会把它们说出来,嘴也会动。
- 按 🧠 Wake up the brain,等到 100%。第一次要下载 869 MB,以后只要几秒钟。然后输入一个问题,按 Ask。
- 按 🎤,大声问出你的问题,再按 ⏹️。第一次,耳朵要下载 41 MB,Chrome 会问这个网页能不能用你的麦克风。
- 要停下服务器,就在终端里按 Ctrl + C。
为什么要网页服务器?直接从文件打开的网页启动不了它的 worker,所以它的大脑和耳朵运行不了。由 Python 来提供这个网页,它们就能运行了。--bind 127.0.0.1 的意思是只有你自己的电脑能打开它。
avatar/avatar.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My talking avatar</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🐷</text></svg>">
<style>
body { font-family: sans-serif; background: #fffaf0; color: #262052; text-align: center; margin: 20px; }
canvas { width: 300px; height: 300px; background: #c9ecff; border: 3px solid #262052; border-radius: 24px; }
#words { min-height: 3em; max-width: 420px; margin: 10px auto; font-size: 18px; }
input, button { font-size: 18px; padding: 6px 12px; margin: 4px; }
</style>
</head>
<body>
<h1>My talking avatar</h1>
<canvas id="face" width="300" height="300"></canvas>
<p id="words">Type something and press Say. Then wake up my brain!</p>
<p><input id="question" placeholder="Type here"> <button id="say">Say</button> <button id="mic">🎤</button></p>
<p><button id="wake">🧠 Wake up the brain</button></p>
<p id="status"></p>
<!-- The brain and the ears each run in a worker: a second small program beside
the page, so the face never freezes while they think. Their code is here. -->
<script type="text/plain" id="brain-code">
import { WebWorkerMLCEngineHandler } from "https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.85/lib/index.js";
const handler = new WebWorkerMLCEngineHandler();
self.onmessage = (message) => handler.onmessage(message);
</script>
<script type="text/plain" id="ears-code">
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0/+esm";
const ears = await pipeline("automatic-speech-recognition", "onnx-community/whisper-tiny.en", { dtype: "q8", device: "wasm" });
self.postMessage("ready");
self.onmessage = async (message) => {
const heard = await ears(message.data);
self.postMessage(heard.text);
};
</script>
<script type="module">
// ---------- 1. Make it yours: change these three ----------
const NAME = "Pip";
const SKIN = "#ffb6cc";
const ABOUT = "You are Pip, a friendly piglet who helps children learn Python. " +
"Answer in one or two short, simple sentences.";
// ---------- 2. The face: drawn again about 60 times a second ----------
const pen = document.getElementById("face").getContext("2d");
let talking = false;
function oval(x, y, wide, high, colour) {
pen.beginPath();
pen.ellipse(x, y, wide, high, 0, 0, Math.PI * 2);
pen.fillStyle = colour;
pen.fill();
pen.lineWidth = 4;
pen.strokeStyle = "#262052";
pen.stroke();
}
function draw(time) {
const seconds = time / 1000;
let mouth = 0; // 0 is shut, 1 is wide open
if (talking) {
mouth = 0.5 + 0.5 * Math.sin(seconds * 18); // open, shut, open: about three times a second
}
let eye = 14;
if (seconds % 4 > 3.85) {
eye = 1; // a blink, every four seconds
}
pen.clearRect(0, 0, 300, 300);
oval(80, 70, 30, 40, SKIN); // ears
oval(220, 70, 30, 40, SKIN);
oval(150, 160, 115, 105, SKIN); // head
oval(105, 130, 14, eye, "#262052"); // eyes
oval(195, 130, 14, eye, "#262052");
oval(150, 175, 38, 26, "#ff8fab"); // snout
oval(137, 175, 6, 9, "#262052"); // nostrils
oval(163, 175, 6, 9, "#262052");
oval(150, 225, 22, 3 + 18 * mouth, "#8c2a48"); // mouth: taller as it opens
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
// ---------- 3. The voice: the browser's own ----------
function say(text) {
document.getElementById("words").textContent = NAME + ": " + text;
speechSynthesis.cancel();
const line = new SpeechSynthesisUtterance(text);
const voices = speechSynthesis.getVoices().filter((voice) => voice.lang.startsWith("en"));
line.voice = voices.find((voice) => voice.name.startsWith("Google")) || voices[0] || null;
line.onstart = () => { talking = true; };
line.onend = () => { talking = false; };
line.onerror = () => { talking = false; };
speechSynthesis.speak(line);
}
// The brain and the ears: each worker is made from the code in its box above.
function workerFrom(id) {
const code = document.getElementById(id).textContent;
const file = new Blob([code], { type: "text/javascript" });
return new Worker(URL.createObjectURL(file), { type: "module" });
}
// ---------- 4. The brain: a small AI model, run in this browser by WebLLM ----------
const MODEL = "Qwen2.5-1.5B-Instruct-q4f16_1-MLC";
const status = document.getElementById("status");
const chat = [{ role: "system", content: ABOUT }];
let brain = null;
async function wakeBrain() {
if (!navigator.gpu) {
status.textContent = "This browser has no WebGPU. Try Chrome or Edge on a computer.";
return;
}
const webllm = await import("https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.85/lib/index.js");
brain = await webllm.CreateWebWorkerMLCEngine(workerFrom("brain-code"), MODEL, {
initProgressCallback: (report) => {
status.textContent = "Brain loading: " + Math.round(report.progress * 100) + "%";
},
});
status.textContent = "My brain is awake. Ask me something!";
document.getElementById("say").textContent = "Ask";
}
async function answer(question) {
chat.push({ role: "user", content: question });
document.getElementById("words").textContent = NAME + " is thinking…";
const recent = [chat[0], ...chat.slice(1).slice(-6)]; // what it was told, and the last few turns
const reply = await brain.chat.completions.create({ messages: recent, max_tokens: 100, temperature: 0.4 });
const text = reply.choices[0].message.content;
chat.push({ role: "assistant", content: text });
say(text);
}
document.getElementById("wake").addEventListener("click", wakeBrain);
document.getElementById("say").addEventListener("click", () => {
const box = document.getElementById("question");
const text = box.value.trim();
box.value = "";
if (text === "") {
return;
}
if (brain) {
answer(text);
} else {
say(text); // no brain yet: it just says your words
}
});
// ---------- 5. The ears: Whisper, a small speech model, run in this browser ----------
const mic = document.getElementById("mic");
let ears = null;
let recorder = null;
function hear(sound) { // give the ears the sound; wait for the words
return new Promise((done) => {
ears.onmessage = (message) => done(message.data);
ears.postMessage(sound);
});
}
async function listen() {
if (recorder) {
recorder.stop(); // pressed again: stop listening
return;
}
if (!ears) {
status.textContent = "Ears loading…";
ears = workerFrom("ears-code");
await new Promise((ready) => { ears.onmessage = ready; });
status.textContent = "Ears ready.";
}
speechSynthesis.cancel();
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const pieces = [];
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (event) => pieces.push(event.data);
recorder.onstop = async () => {
stream.getTracks().forEach((track) => track.stop());
recorder = null;
mic.textContent = "🎤";
const box = new AudioContext({ sampleRate: 16000 }); // Whisper hears 16,000 numbers a second
const sound = await box.decodeAudioData(await new Blob(pieces).arrayBuffer());
const words = (await hear(sound.getChannelData(0))).replace(/\[.*?\]/g, "").trim();
document.getElementById("question").value = words;
document.getElementById("say").click();
};
recorder.start();
mic.textContent = "⏹️"; // talk, then press it to stop
}
mic.addEventListener("click", listen);
</script>
</body>
</html>
🇬🇧 English
The page is HTML, and its program is JavaScript, the browser's own language, in five parts.
1. Make it yours. NAME, SKIN and ABOUT are the avatar's name, its colour, and what the brain is told about who it is.
2. The face. draw() paints the face with oval(), a coloured oval with a dark edge. Then requestAnimationFrame asks the browser to call draw() again for the next picture, about 60 times a second. While talking is true, Math.sin opens and shuts the mouth.
3. The voice. say() gives the words to an English voice of the browser, a Google one if there is one. onstart and onend set talking, so the mouth moves only while the voice speaks. A browser never lets a page hear its voice, so the mouth follows the time, not the sound.
4. The brain. wakeBrain() loads WebLLM and the model in a worker: a second small program beside the page, so the face never freezes while the brain thinks. The worker's code is in the box brain-code at the top, and workerFrom() turns that box into a file the browser can start. answer() gives the brain ABOUT and the last few turns, then says its reply.
5. The ears. listen() records you with MediaRecorder until you press the button again. Whisper, in the worker ears-code, hears the sound as 16,000 numbers a second and gives back the words, and they are asked like typed words.
The brain is small, so it is sometimes wrong: check what it says.
🇹🇭 ไทย
หน้านี้เป็น HTML และโปรแกรมของมันเป็น JavaScript ภาษาของเบราว์เซอร์เอง แบ่งเป็นห้าส่วน
1. ทำให้เป็นของคุณ NAME, SKIN และ ABOUT คือชื่อของอวตาร์ สีของมัน และสิ่งที่บอกสมองว่ามันเป็นใคร
2. หน้า draw() วาดหน้าด้วย oval() ซึ่งเป็นวงรีมีสีและมีขอบสีเข้ม แล้ว requestAnimationFrame ขอให้เบราว์เซอร์เรียก draw() อีกครั้งสำหรับภาพถัดไป ประมาณ 60 ครั้งต่อวินาที ระหว่างที่ talking เป็น true Math.sin จะทำให้ปากเปิดและปิด
3. เสียง say() ส่งคำพูดให้เสียงภาษาอังกฤษของเบราว์เซอร์ ถ้ามีเสียงของ Google ก็ใช้เสียงนั้น onstart และ onend ตั้งค่า talking ปากจึงขยับเฉพาะตอนที่เสียงกำลังพูด เบราว์เซอร์ไม่เคยให้หน้าเว็บได้ยินเสียงของมัน ปากจึงขยับตามเวลา ไม่ใช่ตามเสียง
4. สมอง wakeBrain() โหลด WebLLM และโมเดลใน worker: โปรแกรมเล็ก ๆ อีกตัวที่ทำงานข้างหน้าเว็บ หน้าจึงไม่ค้างตอนที่สมองกำลังคิด โค้ดของ worker อยู่ในกล่อง brain-code ด้านบน และ workerFrom() เปลี่ยนกล่องนั้นเป็นไฟล์ที่เบราว์เซอร์เริ่มได้ answer() ให้ ABOUT และการคุยไม่กี่รอบล่าสุดกับสมอง แล้วพูดคำตอบของมัน
5. หู listen() อัดเสียงของคุณด้วย MediaRecorder จนกว่าคุณจะกดปุ่มอีกครั้ง Whisper ใน worker ears-code ได้ยินเสียงเป็นตัวเลข 16,000 ตัวต่อวินาที แล้วส่งคำกลับมา คำเหล่านั้นถูกถามเหมือนคำที่พิมพ์
สมองตัวเล็ก มันจึงผิดได้บางครั้ง: ตรวจสิ่งที่มันพูดด้วย
🇨🇳 中文
这个网页是 HTML,它的程序是 JavaScript,浏览器自己的语言,分成五个部分。
1. 变成你的。NAME、SKIN 和 ABOUT 是虚拟形象的名字、它的颜色,还有告诉大脑它是谁的话。
2. 脸。draw() 用 oval() 画脸,oval() 画一个有颜色、边是深色的椭圆。然后 requestAnimationFrame 请浏览器为下一张画再调用一次 draw(),大约每秒 60 次。talking 是 true 的时候,Math.sin 让嘴一张一合。
3. 声音。say() 把话交给浏览器的一个英语声音,有 Google 的声音就用 Google 的。onstart 和 onend 设置 talking,所以只有声音在说话的时候嘴才动。浏览器从来不让网页听到它的声音,所以嘴跟着时间动,不是跟着声音动。
4. 大脑。wakeBrain() 在一个 worker 里加载 WebLLM 和模型:worker 是在网页旁边运行的另一个小程序,所以大脑思考的时候脸不会卡住。worker 的代码在上面的 brain-code 框里,workerFrom() 把这个框变成浏览器能启动的文件。answer() 把 ABOUT 和最近几轮对话交给大脑,再把它的回答说出来。
5. 耳朵。listen() 用 MediaRecorder 录你的声音,直到你再按一次按钮。在 worker ears-code 里的 Whisper 把声音听成每秒 16,000 个数字,再把文字交回来,这些文字就像打出来的字一样被问出去。
大脑很小,所以有时会说错:要检查它说的话。
Try it ลองดู 试一试
Make a character of your own. Change NAME, SKIN and ABOUT: a cat called Mali who loves maths, say. Save the file and reload the page. Then change the drawing in draw(): move the ears, make the eyes bigger, or take the snout away. Can you make the eyes look to one side?สร้างตัวละครของคุณเอง เปลี่ยน NAME, SKIN และ ABOUT เช่น แมวชื่อ Mali ที่ชอบคณิตศาสตร์ บันทึกไฟล์แล้วโหลดหน้าใหม่ จากนั้นเปลี่ยนภาพใน draw(): ย้ายหู ทำตาให้ใหญ่ขึ้น หรือเอาจมูกหมูออก คุณทำให้ตามองไปด้านข้างได้ไหม?做一个你自己的角色。改一改 NAME、SKIN 和 ABOUT,比如一只叫 Mali、喜欢数学的猫。保存文件,再刷新网页。然后改改 draw() 里的画:挪一挪耳朵,把眼睛画大一点,或者把猪鼻子拿掉。你能让眼睛往旁边看吗?