diff --git a/.gitignore b/.gitignore
index 9a697e0..71c3ca5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,4 +4,6 @@ __pycache__/*
*~
.DS_Store
.idea/*
-*_build*
\ No newline at end of file
+*_build*
+.vscode/
+**/__pycache__/*
\ No newline at end of file
diff --git a/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md b/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md
index 001a98c..58452c5 100644
--- a/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md
+++ b/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md
@@ -4,131 +4,131 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Basic description of the Python programming language, Difficulty: Easy, Category: Background
:keywords: python, install, basics, scripts, interpreter, foundations
-```
+
-# Introducing the Python Programming Language
+# 介绍Python编程语言
-In this section we will learn
+在本节中我们将学习
- - What Python is.
- - What it means to "install Python" on your computer.
- - How one writes and executes Python code.
+ - Python是什么。
+ - “安装Python”具体意味着什么。
+ - 如何写和执行Python代码。
-## What is Python?
-**Python is a programming language**. That is, it provides us with a strict set of grammatical rules that correspond to well-defined instructions that a computer will obey. The tremendous value of this is that we can write text documents that are relatively simple and intuitive for humans to read, and yet can inform the computer to perform precise operations. Python **code** is simply text that conforms to the Python language.
+## Python是什么?
+**Python是一门编程语言**。具体来讲,Python为我们提供一组严谨的语法规则;每条规则都对应一组计算机会执行的明确命令。这将允许我们编写一些即易读,又能提供具体命令给计算机的文本。所谓的Python**代码**其实就是符合Python语法的文本。
-For example, the following text obeys the rules of the Python language:
+比如说,以下的文本就符合Python的语法规则:
```python
x = 2 + 3
print('2 + 3 = {}'.format(x))
```
-According to the Python language, it will instruct the computer to:
+根据Python的定义,它将指令计算机去:
- - compute 2 + 3
- - assign the resulting value (5) to a variable `x`, in memory
- - access the value of `x`, and print to the computer's screen: '2 + 3 = 5'
+ - 计算 2 + 3
+ - 在内存中设定一个函数 `x` 为计算的结果(5)
+ - 访问 `x` 的值,并在计算机屏幕上显示:“2 + 3 = 5”
-An example of code that **does not** obey Python's rules is:
+一个**不符合**Python规则的例子:
```python
x = 2 ~ 3
```
-because character `~` has no meaning in the Python language when it is placed between two integers.
+原因是,根据Python定义,夹在两个整数中间的符号 `~` 没有任何意义。
-To "learn Python" thus entails learning the grammatical rules specified by the Python language, and the computer instuctions that they map to. Additionally, you will want to familiarize yourself with many of the convenient tools that are "pre-written" and come with the Python language; they are part of the so-called standard library.
+因此,“学习Python”意味着学习Python语言的语法规则以及这些规则对应的计算机指令。同时,你也需要了解已经“提前写好”的,极其方便的Python自带的工具;这些工具是所谓Python标准库的一部分。
-Given this basic understanding of what the Python programming language is, we now want to know how to use our Python code to send instructions to the computer. The most basic way of doing this is to:
+有了对Python语言的基本理解后,我们现在要学习如何使用我们的Python代码去给计算机发送指令。最基本的方法是:
- - Write a Python "script": a text file containing Python code.
- - Pass this text file to a **Python interpreter**, which will instruct the computer to carry out the operations described by the code.
+ - 写Python“脚本”:一个包含Python代码的文本。
+ - 将这个文本送到**Python直译器**(Python Interpreter)中。直译器将告诉计算机去执行代码描述的工作。
-## Python Scripts
-You can save the the valid code from the preceding section in a text file using a simple text editor, and *voilà* you have written a **Python script**: a text file containing Python code. It is standard to save this text file using the suffix `.py` (e.g. `my_code.py`), rather than the familiar `.txt` (e.g. `my_text.txt`). There is nothing special about the `.py` suffix; it simply helps differentiate files that contain Python code from run-of-the-mill text files, which contain plain English.
+## Python脚本
+你可以用任意一个文本编辑器将前文的能用的代码存到一个文本文件中。就像这样,你写好了一个**Python脚本**:一个包含Python代码的文本文件。标准情况下,Python代码的后缀都是 `.py`(比如说 `my_code.py`),而不是常见的 `.txt`(例如 `my_text.txt`)。这个 `.py` 后缀没有任何特殊的;这仅仅是为了帮助用户区分包含Python代码的文本文件和其他正常的包含普通文章的文本文件。
-Although you can use simple text editors to write Python scripts (e.g. notepad (Win), TextEdit (Mac), nano (Linux)), there are much more sophisticated editors that provide an "integrated development environment" (IDE) for writing code. An IDE, configured to support Python, will warn you if you have written code that violates Python's grammar rules, similar to the way word processing software warns you if you have made a spelling mistake. More on IDEs in a later section.
+虽然你可以使用基本的文本编辑器去写Python脚本(如notepad(Windows),TextEdit(Mac),nano(Linux)),但是你也可以使用更加复杂的提供“集成开发环境”(Integrated Development Environment,也就是IDE)的编辑器来写代码。一个为Python配置的IDE会警告不符合Python语法的代码,就像Word这类文字处理软件会提醒你的错误拼写一样。我们会在之后的一节里详细讨论IDE。
-**WARNING**:
+**警告**:
+
+不要使用像Microsfot Word这样的传统文字处理程序来编写代码。这些程序会“静默”地对你打出的字符进行修改,如双引号的种类。这会导致你的代码出现错误。
-Do not use word processing programs, like Microsoft Word, to write code. They will "silently" change the characters written in your file, such as the type of quotation marks being used. This will cause errors in your code.
+译者注:在写Python代码时一定要记得使用英文输入法。Python直译器并不会理解中文的双引号 “” 或单引号 ‘’
-Now that you have a Python script, how do you get the computer to read it and follow its instructions? You will need to install a **Python interpreter** on your computer to accomplish this. This is what people mean, whether they know it or not, when they tell you to "install Python" on your computer.
+在有一个Python脚本后,该如何让电脑读取并执行脚本的指示呢?你需要在你的计算机上安装一个**Python直译器**。当人们说你需要“安装Python”的时候,这就是他们具体的意思。
-
-## What is a Python Interpreter and What Does it Mean to "Install Python"?
-A Python interpreter is any computer program that is capable of doing the following:
+## Python直译器是什么?“安装Python”意味着什么?
- - Read in a text file (e.g. `my_code.py`).
- - Parse the text and determine if it obeys the rules of the Python language (the interpreter will raise an error if the rules are not obeyed).
- - Translate the parsed text into instructions, according to the Python language's specifications.
- - Instruct the computer to carry out the tasks.
- - As a whole, a Python script is executed from top-to-bottom by the interpreter.
+Python直译器泛指任何可以执行以下的电脑程序:
-The first Python interpeter was written in the programming language C, and is known as CPython. Accordingly, **the CPython interpreter is the official interpreter of the Python language**. Any new rules/features that are introduced to the Python language are guaranteed be implemented in the [CPython code base](https://github.com/python/cpython).
+ - 读取文本文件(如 `my_code.py`)。
+ - 解析其文本并反馈文本是否符合Python语言的语法规则(如果不符合,直译器会报错)。
+ - 指示计算机去执行文本描述的任务。
+ - 总体而言,Python直译器将从上到下执行脚本。
+
+世界上第一个Python直译器是用C编程语言写的,因此其被命名为CPython。所以**CPython直译器是最官方的Python语言直译器**。任何新的Python特征或规则一定会在[CPython代码库](https://github.com/python/cpython)中实现。
-**Note**:
+**注**:
-Python interpreters have been in written programming languages other than C, like in Java (Jython) and Go (Grumpy). These are not guaranteed to be up-to-date with the latest specifications of the Python language, and are rarely used in comparison to the CPython interpreter.
+当然,Python直译器也存在于其他不是C的编程语言中,如Java(Jython)和Go(Grumpy)。这些直译器并不能保证实现最新的Python规范,因此很少有人会将它们和CPython直译器对比。
-**About Installing Python**:
+**关于安装Python**:
-Do not download and install Python from python.org. There isn't anything wrong with this, but a later section will provide you with explicit instructions for installing Python on your machine.
+不要从python.org下载和安装Python。这样做没有任何错,但是本文后面的一节将提供详细的Python安装指示。
-If you "install Python on your computer" from [python.org](https://www.python.org/downloads/release/python-363/), you are essentially downloading an executable program onto your machine that operates as a Python interpreter. On Windows, for instance, this program is called `python.exe`. This program is the result of the aforementioned CPython code, and it is capable of performing the all of the tasks of a Python interpreter. Additionally, you are downloading a large suite of useful tools and functions that you can utilize in your code. This is known as the Python standard library; take a moment to look over its contents [here](https://docs.python.org/3/library/index.html#the-python-standard-library).
+如果你从[python.org](https://www.python.org/downloads/release/python-363/)“在你的计算机上安装了Python”,你在做的基本就是下载一个满足Python直译器规范的可执行文件。比如在Windows上,这个程序叫做 `python.exe`。这个程序就是之前提到的CPython代码的产物,其可以执行任何Python直译器的工作。同时,你也在下载一大组可以用于你自己代码里的工具和函数。这些工具和函数叫做Python标准库;花一些时间去了解[标准库](https://docs.python.org/3/library/index.html#the-python-standard-library)的内容。
-Once you have a Python interpreter installed on your machine, using it to execute a Python script is quite simple. Assume for the sake of simplicity that the `python` interpreter program and `my_script.py` are in the same directory (a.k.a 'folder') in your computer. Then, in a terminal (`cmd.exe` for Windows) you can execute the following command:
+当你在计算机上安装了一个Python直译器后,使用它去执行Python脚本并不困难。为简化我们的讨论,假设叫做 `python` 的直译器程序和 `my_script.py` 都在你的计算机中同一个文件夹内(叫做 `folder`)。那么,在命令行(对Windows而言就是 `cmd.exe`)中,你可以执行以下指令:
```shell
python my_script.py
```
-this will instruct the Python interpreter program `python` to read your text file `my_script.py`, ensure that your code obeys all of the grammatical rules specified by the Python language, and then send instructions to your computer in accordance with the code that it reads. If your script simply contains the code `print("hello world")`, then the text `hello world` will appear in your terminal window, as expected.
+这将指示Python直译器程序 `python` 去读取你的文本文件 `my_script.py`,确保里面的代码符合所有Python语言的语法规则,并指示你的计算机去执行和文本相应的指令。如果你的脚本仅仅包含代码 `print("hello world")`,那么你的命令行自然会显示字符串 `hello world`。
-In practice, you will be able to simply execute `python my_script.py` in any directory, and your computer will know where to look to find the `python` program. This will be set up during the installation process.
+在实际使用中,不管你从任何文件夹中执行 `python my_script.py`,你的计算机也应该会知道如何去找到名为 `python` 程序。相应的设置会在安装过程中完成。
-It may be confusing to think that the Python language is interpreted by using a program written in another language. How, then, is that language interpreted? The answer, in the case of CPython, is that C code need not be interpreted; programs exist for Windows, Mac, and Linux that can translate C code directly into machine instructions.
-
+理解Python语言是被一个用另外语言编写的程序来直译的事实可能比较绕脑。如果是这样,那另外那个语言是怎么被直译的呢?在CPython的情况下,答案就是C代码并不会被直译;有程序存在于Windows,Mac,和Linux上可以直接将C代码翻译成电脑直接执行的机器指令。
-## Why Python?
+## 为什么选择Python?
-Python has become a hugely popular programming language. In fact, it is likely the [most popular introductory language at universities](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext). First and foremost, its syntax is designed to be intuitive and readable. For example, the following Python code sums the numbers 0-9, and prints the result:
+Python已经成为了一个极其流行的编程语言。事实上,它可能是[最流行的大学编程入门语言](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext)。首先,Python的句法非常易懂易读。比如说,接下来的代码会求数字 0-9 的和,并打印结果:
```python
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(sum(a))
```
-This can be reproduced by the following C++ code, which is arguably less-intuitive:
+同样的工作可以用以下的C++代码达成,但是这难懂很多:
```cpp
#include
#include
@@ -136,21 +136,21 @@ This can be reproduced by the following C++ code, which is arguably less-intuiti
int main() {
std::vector a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
- std::cout << std::accumulate(a.begin(), e.end(), 0) << std::endl;
+ std::cout << std::accumulate(a.begin(), a.end(), 0) << std::endl;
}
```
-As such, Python is a language that is conducive to rapidly prototyping and testing code. Additionally, it is open-sourced: it is free to use, anyone can participate in improving/maintaining the language, and many people create new libraries that add tremendous functionality to the language. Thus, Python has become exceptionally popular especially among scientists, engineers, and other researchers.
+因此,Python作为一门语言很方便快速编写和测试新代码。同时,Python是开源的;你可以免费使用它,任何人都可以参与到维持或改善这门语言中,且大家创造了很多给Python提供了大量功能的第三方模组。因此,Python在科学家,工程师,和其他研究者中极其流行。
-We will be relying heavily on Python and a library for doing optimized numerical computations, called NumPy, throughout this course.
+在本资源中我们会使用Python和高度优化的数字工作模组NumPy。
-## Summary
+## 总结
-- Python is a programming language - it provides us with a simple set of grammatical rules that allow us to write human-readable text, which can be translated unambiguously to instruct a computer to perform tasks.
-- Python code is text that conforms to the Python language.
-- A Python script is a text file containing Python code. Traditionally such a file will be saved using the suffix `.py`.
-- A Python interpreter is a program that is capable of reading and parsing a text file, and translating the code into machine instructions, as specified by the Python language.
-- To "install Python" onto you machine boils down to saving a functioning Python interpreter onto your machine.
-- The official Python interpreter is a program written in the language C, and is known as the CPython interpreter.
-- The "standard library" is a large collection of tools and functions that comes packaged with the CPython interpreter.
+- Python是一门编程语言——它为我们提供一组简单的语法规则来编写既可以让人看懂也可以准确翻译到计算机指令的文本。
+- Python代码是任何符合Python语言标准的文本。
+- Python脚本是一个包含Python代码的文本文件。这种文件根据命名标准都使用后缀 `.py`。
+- Python直译器是一个能够读取和分析文本文件并根据Python语言的规则将其中的代码翻译成计算机指示的程序。
+- "安装Python”归根结底就是将Python直译器下载到你的计算机上。
+- 官方的Python直译器是一个用C语言编写的程序,叫做CPython直译器。
+- Python"标准库“是和CPython直译器一起包装的一组庞大的工具和函数。
diff --git a/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md b/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md
index c1ada19..3fd82ae 100644
--- a/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md
+++ b/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md
@@ -4,84 +4,79 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Integrated Development Environments, Difficulty: Easy, Category: Tools
:keywords: python, introduction, IDE, PyCharm, VSCode, Jupyter, recommendation, tools
-```
+
-# Setting Up a Development Environment
-## What You Will Learn
+# 设置开发环境
+## 你将学到什么
-- An IDE is a sophisticated text editor that allows you edit, run, and debug code.
-- The Python shell is an interface for typing Python code and executing it directly in your computer's terminal.
-- The IPython shell is a much nicer version of the Python shell - it provides syntax highlighting, autocompletion, and other features.
-- The Jupyter Notebook is a powerful tool for prototyping and experimenting with code, as well as visualizing data and writing nicely-formatted text. We will be using this throughout the course.
+- 集成开发环境(IDE)是一套用来编辑,运行,和调试代码的复杂的文本编辑器。
+- Python壳(shell)是一个用以输入和直接在计算机命令行中运行Python代码的接口。
+- IPython壳是一个更加完善的Python壳——它提供语法高亮,自动完成,以及其它有用的功能。
+- Jupyter记事本是用来编写,测试新代码的强大工具。它同时也可以用来可视化数据和编写格式化的文本。我们将会在本资源中经常使用它。
-## Integrated Development Environments
-In Section 1 of this module, we learned that a Python script is simply a text file that contains Python code. Aside from using a `.py` suffix for the filename, there is nothing that differentiates this sort of file from any other text file. That being said, it is not a good idea to use a simple text editor to write Python code (and it is a big mistake use word-processing software, like Microsoft Word, to do so). Instead we want an "integrated development environment" (IDE) that will facilitate our code-writing.
+## 集成开发环境(IDE)
+在本模组的第一节中,我们了解了Python脚本仅仅是包含Python代码的文本文件这一事实。除了使用 `.py` 为文件后缀名之外,Python脚本对比其它文本文件没有什么特殊的特征。话说如此,使用文本编辑器来编写Python代码很不效率(而使用Microsoft Word这样的文字处理软件是万万不可取的)。我们需要一个“集成开发环境”(IDE)来帮助我们开发代码。
-First and foremost, a good IDE will provide a text editor that will:
+首先,一个好的IDE会提供拥有如下功能的文本编辑器:
-- check your code for syntax errors (a misspelled function name, a reference to an undefined variable, etc)
-- colorize your code so that it is easy to distinguish, for instance, numbers from character strings.
-- enable you to easily look up documentation and definitions for functions that you are using.
-- autocomplete the names of variables and functions as you are typing them.
+- 检查你的代码并标记语法错误(如拼错的函数名,不存在的变量,等等)
+- 彩色化你的代码来使其更容易分辨。比如说,这可以帮助你区分数字和字符串。
+- 允许你轻松地查阅函数的定义和说明文件。
+- 在你输入变量和函数时自动完成它们的名字。
-An IDE also often provides debugging tools so that you can test your code; it will also typically interface with version-control software, like Git, so that you can keep track of versions of your code as you modify it. We will not discuss these useful, but more advanced features here.
+很多IDE也会提供帮助你测试你的代码的调试工具以及帮助你在修改代码的同时记录代码版本的版本控制软件(version-control software)(如Git)。虽然它们很有用,我们在此并不讨论这些高级功能。
-### Recommended IDEs
-There are many excellent IDEs that can be configured to work well with Python. Two IDEs that we endorse are:
+### 推荐的IDE
+市面上有很多IDE支持Python代码。我们在这里推荐两个:
-[PyCharm](https://www.jetbrains.com/pycharm/download): A powerful IDE dedicated to Python.
+[PyCharm](https://www.jetbrains.com/pycharm/download): 一个专门针对Python开发的强大IDE。
-**Pros**
+**好处**
-- works well out-of-the-box
-- long-supported by professionals and thus is very reliable
-- highly configurable
-- fully-featured
+- 下载即用,无需太多设置就很好用
+- 有职业人员的长期支持,因此很可靠
+- 可以进行深层次的设置
+- 全功能,包括极棒的调试器,适应语境的“Intellisense”,类型推论
+- 免费的“社区版本”(community version)已经非常强大和活跃
-**Cons**
+**坏处**
- - can be resource-heavy, especially for a laptop
- - may be overwhelming to new users (but has good documentation and tutorials)
-
-[Visual Studio Code](https://code.visualstudio.com/) with the [Python extension](https://code.visualstudio.com/docs/languages/python): A lightweight, highly customizable IDE.
-
-**Pros**
+ - 很耗资源,特别对手提电脑而言
+ - 功能多导致新用户难以上手(但它有很好的教程和说明文件)
+ - 需要付费版的PyCharm才可以支持Jupyter记事本,因此对新用户不友好
-- lightweight and elegant
-- works with many different languages, so you only need to familiarize yourself with one IDE
-- a huge number of extensions can be downloaded to add functionality to the editor; these are created by a large community of open-source developers.
+[Visual Studio Code](https://code.visualstudio.com/) 以及它的 [Python拓展](https://code.visualstudio.com/docs/languages/python): 一个轻便,宜定制的IDE。
-**Cons**
+**好处**
-- currently less polished and less powerful than PyCharm, although Microsoft is now formally supporting the Python extension
-- can require some tinkering to get features working
+- 轻便优雅
+- 完全免费
+- 支持其它的编程语言,就算你经常使用多种编程语言你也只需要学习使用一个IDE
+- 有极其多的拓展可供下载以提供编辑器新功能;这些拓展是由一个大社区的开源开发者编写的
+- [支持Jupyter记事本](https://code.visualstudio.com/docs/python/jupyter-support),意味着你可以在记事本中享受VSCode的intellisense,调试器,和查看变量的功能
+**坏处**
-
-
-**Takeaway**:
+- 设置VSCode来进行Python开发对新手而言可能相对复杂
+- 很多功能,如intellisense和类型推论,在PyCharm中更加完善和强大
-Integrated Development Environments (IDEs) provide powerful tools for helping you write well-formatted and typo-free code. We recommend using PyCharm Community Edition or Visual Studio Code (with the Python extension installed) for your Python IDE.
-
+
-
-
-**Jupyter Lab**:
-
-[Jupyter Lab](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html) is a new IDE that is being developed by the same team that develops the Jupyter Notebook. It aims to mix the polish and power of a traditional IDE, along with the convenience and great utility of the notebook environment. As of writing this, Jupyter Lab is still in the beta release phase. Given the massive popularity of Jupyter Notebook, Jupyter Lab will likely become a widely used IDE, quickly.
+**经验**:
-
+集成开发环境(IDE)提供强大的工具来帮助你编写格式化和无拼写错误的代码。本资源建议你使用PyCharm Community Edition或Visual Studio Code(加上Python拓展)作为你的Python IDE。
+
\ No newline at end of file
diff --git a/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md b/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md
index aa53eea..a71eb5b 100644
--- a/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md
+++ b/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md
@@ -4,132 +4,134 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Informal Introduction to Python, Difficulty: Easy, Category: Tutorial
:keywords: python, installation, script, introduction, ipython, console, quick introduction
-```
+
-# An Informal Introduction to Python
-Now that you have the Anaconda distribution of Python installed on your machine, let's write some simple Python code! We are going to forego writing a full Python script for now, and instead make use of a convenient tool for doing quick code scratchwork. The IPython console was installed as a part of Anaconda; it will allow us to build incrementally off of snippets of code, instead of having to execute an entire script all at once.
+# 非正式的Python介绍
+在你下载好了Anaconda版本的Python之后,让我们来写一些简单的Python代码吧!我们暂时先不编写完整的Python脚本,而只用一个方便的工具——IPython命令行——来快速地尝试一些简单的代码。Anaconda一并安装了IPython命令行;这将帮助你一步步增加代码片段,而不是要一次性执行整个脚本。
-Let's open an IPython console. Open your terminal if you are a Mac/Linux user, or start `cmd.exe` if you are a Windows user. Now type `ipython` into the console and hit ``. You should see the following display on your screen:
+让我们打开IPython命令行。如果你是Mac或者Linux用户,打开你的命令行;如果你是Windows用户,打开 `cmd.exe`。输入 `ipython` 并敲击回车,你应该可以在屏幕上看到接下来的内容:

-We can type small pieces of Python code into this console, and then simply hit `` to have the CPython interpreter execute our code immediately within the IPython console!
+当我们输入简短的Python代码片段并输入回车时,CPython直译器会在IPython命令行中瞬间执行你的代码。
-Let's acquaint ourselves with Python's numbers, strings, and lists. In doing so, we will learn about the Python standard library, and how to make use of its modules, like the math module. IPython's autocompletion and documentation-display utilities will provide a nice means for exploring the library and the functionality built into the different types of Python objects. A quick glimpse at Python's strings and lists will hint at the common interface Python provides for working with sequences of objects, while highlighting some of the nice features of these all-important data types.
+让我们熟悉一下Python的数字(number),字符串(string),和列表(list)。在这个过程中,我们会了解Python标准库的一些模组,如math模组。IPython提供的自动完成和说明文档显示功能会帮助我们探索标准库和其中Python对象(object)的功能。尝试使用Python的字符串和列表会帮助我们对Python的通用界面产生印象,并演示这些基本数据类型的方便特征。
-## Dabbling with Numbers
-Time to execute some Python code that performs simple arithmetic. Typing `2 + 3` into the IPython console and hitting the `` key, you should see the following input and output in the console:
+## 玩玩数字
+是时候执行一些简单算术的Python代码了。在IPython命令行中输入 `2 + 3` 并敲击回车,你应该能看到接下来的输入和输出:
```python
2 + 3
```
-This console session is persistent, meaning that we can define a variable and then reference it in our code later on within this console session. Let's define the variable `x` and assign it to the integer `10` (please follow along in the IPython console)
+这个命令行进程是持久性的,也就是说我们定义的变量可以在这个进程之后的代码重新调用。让我们定义变量 `x` 并向其赋值数值整数 `10`(请在命令行中跟随本教程)
```python
x = 10
```
-We can check the contents of `x` in this console by simply entering `x` in the next line and hitting ``:
+我们可以在这个命令行里查看 `x` 的值。在下一行中输入 `x` 并回车:
```python
x
```
-Now, let's use `x` in a quadratic equation $x^{2} + 2x + 3$, and compute this total.
+现在,让我们在二次方程 $x^{2} + 2x + 3$ 中调用 `x`,并计算结果。
```python
x**2 + 2*x + 3
```
-Python's "standard library", the various tools and functions that come packaged as part of the core language, includes plenty of familiar mathematical functions. As a matter of organization, Python stores these mathematical functions away in a module named "math". To make use of this math module, we must import it into our code.
+Python的“标准库”——也就是和Python核心语言一起包装的各种工具和函数——包含了很多常见的数学函数。为了组织和结构,Python将这些数学函数存在一个叫做“math”的模组里。我们必须要在代码里导入(import)这个模组来使用这些函数。
```python
import math
```
-Having imported it, the term `math` now refers to the math module in our code. IPython provides a nice way for us to see a list of all the functions that are provided by the math module. To utilize this, type into the console `math.` (note the trailing period) and then hit ``. You should see this list appear:
+在导入完之后,`math` 这个单词在我们代码里将代表math模组。IPython提供了一个查看math模组所有函数的方便方法。在命令行中输入 `math.`(注意在单词后面的点)并敲击 ``。你应该看到接下来的这个列表:

-In general, hitting `` will cue IPython to try to autocomplete code for you. This menu displays all the valid things that you could type after `math.`. Looking at the functions starting with "s", we see `sqrt()`. This is the square root function. To see autocompletion in action, type `math.sq` and then hit ``. You should see the code autocomplete to `math.sqrt`.
+一般来说,敲击 `` 会使IPython尝试自动完成你的代码。这个列表显示了所有可以在 `math.` 之后输入的内容。在“s”打头的函数中,我们可以看到 `sqrt()`。这就是一个求平方根的函数。输入 `math.sq` 然后在敲击 `` ,你会看到IPython将自动完成你的代码成 `math.sqrt`。
-Let's use this function to compute $\sqrt{100}$:
+让我们用这个函数来计算 $\sqrt{100}$:
```python
math.sqrt(100)
```
-You might wonder why the result displayed as `10.0` and not simply as `10`; in Module 2 we will see that these are two different *types* of numbers in the Python language. The former is called a floating-point number, indicating the presence of its decimal point, whereas the latter is an integer. The `math.sqrt` function is defined such that it always returns its results as floating-point numbers.
+你可能会好奇为什么计算的结果显示的是 `10.0` 而非 `10`;在模组2中我们会了解这两个输出是两种不一样的数据*类型*。前者被称为浮点数,因为小数点是一个漂浮的点,而后者则是一个整数。函数 `math.sqrt` 的定义使得它永远都会返回浮点数。
-In the case that we want to make frequent use of a certain function from the math module, it'd be nice to avoid having to type out the math module prefix, `math.`, repeatedly. We can accomplish this by importing an individual function from the math module. Let's import the factorial function from the math module.
+当我们想要经常使用math模组里的某个函数时,我们可能希望不需要每次都要打出math模组的前缀 `math.`。我们可以通过从math模组导入单独的函数来达成这个目的。我们将从math模组导入阶乘(factorial)函数。
```python
from math import factorial
```
-We can now make use of the `factorial` function in our code. Recall that 5-factorial is $5! = 5\times 4\times 3\times 2\times 1 = 120$
+我们现在可以在代码里直接调用 `factorial` 函数。5的阶乘是 $5! = 5\times 4\times 3\times 2\times 1 = 120$
```python
factorial(5)
```
-## Messing with Strings
-In the context of code, written text is referred to as a string of characters, or string for short. Python is an excellent language for doing text-processing work as it provides many convenient, efficient functions for working with strings.
+## 试试字符串
+在代码中,我们将文字理解为一连串的字符,也就是字符串(string)。因为Python提供了很多方便,高效的字符串处理函数,所以它很适合于文本处理工作。
-To begin, we simply form a string by typing characters between quotation marks:
+让我们先通过在双引号之间敲击字符来创建第一个字符串吧:
```python
"the cat in the hat"
```
-Single quotes also work:
+单引号也可以:
```python
'the dog in the sash'
```
-If you use single quotes to form a string, then that string is able to contain the double-quote as a character (and vice versa):
+译者注:记得切换到英文输入法的引号 '' 和 "" 。中文的 ‘’ 和 “” 是不会被识别的。
+
+如果你使用单引号来创建一个字符串,那么那个字符串就可以含有双引号(反之亦然):
```python
'He picked up the phone, "Hello? What do you want?" Bob was a rather impolite dude.'
```
-There are designated special characters that allow us to affect the way a string is formatted when it is printed to the string. For example, if `\n` ever occurs in a string, it is treated as a single character that indicates a line-break. This will only manifest if such a string is fed to the built-in `print` function, which informs the computer to print text to a user's screen.
+当然,我们也有专门的特殊字符来帮助我们改变一个字符串的被打印出时的格式。比如说,如果 `\n` 出现在字符串中,它会被当为一个代表回车的字符。这仅仅会在你使用自带的 `print` 函数(一个指示计算机将文本显示在用户电脑屏幕上的函数)来打印这个字符串时才会显示,
-Let's create a string that will display as three separate lines, when printed to the screen.
+让我们创建一个会被 `print` 显示为三行文字的字符串。
```python
print("I like to talk to dogs.\nI like to talk to cats.\nWhat's my deal?")
```
-Of course, strings are useful beyond merely containing text! Let's explore some ways to manipulate strings. First, we'll write a string and assign it to a variable named `sentence`:
+当然,字符串的作用远远不及仅仅存储文本!让我们探索一些操作字符串的方法。首先,我们将创建一个字符串并将其存储到一个名为 `sentence` 的变量中:
```python
sentence = "Who would have thought that we were robots all along?"
```
-Let's see how many characters are in this string by checking the "length" of this sequence of characters:
+让我们通过字符串的“length”(长度)来查看这个字符串有几个字符吧:
```python
len(sentence)
```
-We can access the first 4 characters in the string, the last 6 characters, or a few characters in the middle by "slicing" the string:
+我们可以通过切片(slice)这个字符串来查看它的前四个字符,最后六个字符,或者中间的字符。
```python
sentence[:4]
@@ -143,54 +145,54 @@ sentence[-6:]
sentence[5:22]
```
-We can also check to see if some other string is contained within our string. Is the string `"robot"` contained within `sentence`?
+我们也可以查看是否我们的这个字符串是否包含其它的某个的字符串。字符串 `"robot"` 是否在 `sentence` 中呢(is `"robot"` **in** `sentence`)?
```python
"robot" in sentence
```
-As a quick way to check out the built-in functions that strings have available to them, we can make use of IPython's autocompletion feature once again. Type `sentence.` (including the trailing period) and then hit ``. A menu of functions should appear as so:
+为了快速查看所有字符串可以调用的自带函数,我们可以再次使用IPython的自动完成功能。输入 `sentence.`(不要漏掉最后的点)并敲击 ``。我们会看到一列表的函数:

-Let's use the count function to tally the number of lowercase w's in `sentence`
+让我们用名为count的函数来数 `sentence` 中有多少小写的w。
```python
sentence.count('w')
```
-Let's see what the replace function does. IPython provides a great utility for looking up the documentation for a function by simply putting two question marks after the function name. For example:
+让我们看看replace函数是做什么用的。IPython提供一个很方便的看看函数说明文档的功能,只需在函数名后输入两个问号。如下:

-Putting our newfound understanding of the string's replace function, let's replace "robot" with "computer":
+利用我们刚得到的对字符串replace函数的理解,让我们用“computer”来代替“robot”:
```python
sentence.replace("robot", "computer")
```
-## Playing with Lists
-A list is one of several types of containers that are built into Python's standard library. It can hold a sequence of Python objects. We can create a list of numbers:
+## 看看列表
+列表(list)是Python标准库中容器的一种。它可以存储一序列(sequence)的Python对象(object)。我们可以创建一个数字列表:
```python
[-1, 1/3, 10*2, 7-1]
```
-A list can contain any type of Python object; it can store a mix of numbers, strings, other lists, and much more!
+列表可以存储任何类型的Python对象;它可以混合存储数字,字符串,其它列表,和任何类型的对象。
```python
[1, 2, "a", 0.5, "apple and orange"]
```
-You can join lists together, which is known as concatenation.
+你可以将两个列表粘连(concatenate)到一起。
```python
[1, 2, 3] + ["a", "b", "c"]
```
-Like a string, a list is sequential in nature and we can access the items in a list by specifying its position in the sequence. This is known as "indexing" the list; the index of the first item in a sequence is always 0.
+像字符串一样,列表本质上也是一个序列,所以我们可以通过项目在列表中的位置来访问它。这个位置叫做项目的索引(index);序列第一个成员的索引永远都是0.
```python
my_list = [10, 20, 30, 40, 50, 60]
@@ -204,13 +206,13 @@ my_list[0]
my_list[1]
```
-Negative integers can be used to index relative to the end (right-side) of the list.
+你可以使用负整数来相对于列表结尾(右边)来索引。
```python
my_list[-1]
```
-You can change an entry in a list by assigning it to a new value.
+你也可以通过对列表中的项目赋值来修改列表的内容。
```python
-5 in my_list
@@ -228,13 +230,13 @@ my_list
-5 in my_list
```
-We can also access multiple items in a list at once by slicing the list, like we did with the string.
+我们也同样可以通过切片(slice)这个列表来存取其中的多个项目,就像之前的字符串一样。
```python
my_list[:3]
```
-This slice can be used to update the first three entries of the list
+这个切片出的结果可以用来更新列表的前三项内容。
```python
my_list[:3] = "abc"
@@ -244,7 +246,7 @@ my_list[:3] = "abc"
my_list
```
-To wrap up this quick demo, let's append an new entry to the end of this list.
+为这个演示收尾,让我们在这个列表的结尾附加(append)一个新成员。
```python
my_list.append("moo")
diff --git a/Python/Module1_GettingStartedWithPython/Installing_Python.md b/Python/Module1_GettingStartedWithPython/Installing_Python.md
index a932c0a..f19daf4 100644
--- a/Python/Module1_GettingStartedWithPython/Installing_Python.md
+++ b/Python/Module1_GettingStartedWithPython/Installing_Python.md
@@ -4,110 +4,100 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Installing Python with Anaconda, Difficulty: Easy, Category: Tutorial
:keywords: python, anaconda, instructions, environments, beginner, data science, introduction
-```
+
-## Installing Python
+## 安装Python
-Without further adieu, we now provide instructions for installing Python and other useful Python libraries on your machine via the Anaconda platform. Installing the Anaconda platform will install the following:
+废话不多说,让我们提供安装Python和其它有用的Python模组的步骤吧。安装Anaconda平台会安装以下的内容:
- - Python; specifically the CPython interpreter that we discussed in the previous section.
- - A number of useful Python packages, like matplotlib, NumPy, and SciPy.
- - Jupyter, which provides an interactive "notebook" environment for prototyping code.
- - conda: a package manager that will allow you to install and update Python and additional Python packages, while handling all compatibility issues for you.
+ - Python;具体来讲是之前一节提到的CPython直译器。
+ - 一些有用的Python模组,如matplotlib,NumPy,和SciPy。
+ - Jupyter,用以提供用来编写新代码的互动式“记事本”环境。
+ - conda:一个帮助你安装并升级Python和其它Python模组以及自动处理兼容性问题的包管理器。
-Note that installing Python via Anaconda will **not** break any other installations of Python that already exist on your computer. See [What did this just do to my computer?](#What-did-this-just-do-to-my-computer?) for more details.
+请注意通过Anaconda安装Python**不会**破坏通过其他途径安装的Python。详阅[我刚对我的电脑做了什么?](#我刚对我的电脑做了什么?)。
-Some of the packages provided by Anaconda, like NumPy, have been [optimized](https://docs.anaconda.com/mkl-optimizations/) and will run significantly faster than if you installed them manually.
+有些Anaconda提供的模组,如NumPy,是被[优化](https://docs.anaconda.com/mkl-optimizations/)过的,而因此比起单独安装运行得快很多。
-**Takeaway**:
+**经验**:
-"Anaconda" is a collection of the CPython interpreter and a number of very popular Python libraries for doing data science-related work. It also provides a package manager for downloading/updating Python packages, and an environment manager for maintaining independent installations of Python side-by-side.
+“Anaconda”是包含CPython直译器和其它流行Python数据科学模组的集合。它提供一个用来下载和更新Python模组的包管理器,以及一个用以同时维持多个独立Python安装的环境管理器。
-### Installing Anaconda
+### 安装Anaconda
+
+1. 点开[本链接](https://www.anaconda.com/download/),并单击**Python 3**对应的“Download”按钮。
+2. 当下载完成后,安装下载的文件。安装过程中会有个选择:`Add Anaconda to the system PATH environment variable`(将Anaconda加到系统PATH的环境变量中);我建议你**选择**这个选项(懂行的用户:见下以了解关于这个选择的注意事项)。
+3. 完成20分钟的[“Getting Started”](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html)(入门)教程来熟悉 `conda`。这很重要!译者注:这里是英文的文档,有能力的读者可以用谷歌机翻。如果实在看不懂,文章中关于环境管理的内容在本节后面会有包含。
-1. Navigate to [this page](https://www.anaconda.com/download/), and click the "Download" button for **Python 3**.
-2. After the download is complete, begin the installation process. There will be an installation option: `Add Anaconda to the system PATH environment variable`; we advise you to **enable** this installation option (advanced users: see below for caveats).
-3. Complete the 30 minute ["Getting Started"](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html) tutorial to familiarize yourself with `conda`. This is very important!
+你将会需要知道如何打开一个命令行(Windows用户是cmd.exe),以及如何在命令行中切换文件夹。如果你不知道如何做到这些,请阅读一个和你操作系统相对应的教程。译者注:Windows:[文库](https://wenku.baidu.com/view/35c6365c7cd184254a353526.html)(注意要下载券)或[经验](https://jingyan.baidu.com/article/adc815138b23eef722bf7348.html)(不全面,但够用)。
-You will need to know how to open a terminal (cmd.exe for Windows users) on your computer, and how to navigate between directories in the terminal. If you do not know how to do this, read a 'how-to' for whatever operating system you are using.
-
-### What did this just do to my computer?
+### 我刚对我的电脑做了什么?
-This created a directory called `Anaconda3` (or some variant of this) on your computer, which contains all of the files associated with the CPython interpreter, all of the modules in Python's standard library, the aforementioned 3rd party packages that come as part of the Anaconda distribution (e.g. NumPy, SciPy, Jupyter, iPython), and the `conda` package manager. It also contains the executable files for all of these applications. The default install location for Anaconda is:
+这创建了一个叫做 `Anaconda3`(或类似)的文件夹。它包含了所以和CPython直译器有关的文件,所有Python标准库的模组,之前提到过的Anaconda包含的第三方模组(例,NumPy,SciPy,Jupyter,iPython),和 `conda` 包管理器。它也包含了这些所有的程序的可执行文件。默认的Anaconda安装路径为:
-- (Linux): `/home//Anaconda3`
-- (Windows): `C:\Users\\Anaconda3`
-- (Mac): `/Users//Anaconda3`
+- (Linux):`/home//Anaconda3`
+- (Windows):`C:\Users\\Anaconda3`
+- (Mac):`/Users//Anaconda3`
-If you followed the install instructions as specified above, then the Anaconda-installer also *placed this directory in your system's "path"*. Let's briefly discuss what this means. Your system's path is simply a list of directories. Whenever you execute any command in your computer's terminal, the computer will quickly search through the directories that are specified in the path for an executable with that name; *it will execute the first such executable that it finds*. Thus, by placing the `Anaconda3` directory at the beginning of your path, the Anaconda-installer has ensured that your computer will prioritize Anaconda's python executable over any other installations of Python on your computer, because it will find that executable first.
+如果你跟随了上文的安装指示,那么Anaconda安装器应该*将这个文件夹输入到了你系统的“path”环境变量中*。让我们快速地描述一下这具体意味着什么。系统的path是一个文件夹列表。每当你从你计算机的命令行中执行任何指令,你的计算机都会快速搜寻“path”包含的文件夹下面同名的可执行文件;*计算机将会执行它找到的第一个同名可执行文件*。因此,将 `Anaconda3` 文件夹放在path列表的最顶端会导致你的系统最优先使用Anaconda的Python可执行文件,而非任何其它安装的Python版本,因为系统会首先找到Anaconda版本的可执行文件。
-For Linux and Mac users, it is very likely that your system already has a version of Python installed. *It is critical that you do not attempt to uninstall, remove, or change this native version of Python*. Those operating systems use their native versions of Python to perform some of their services. Those services are written such that they will directly invoke the Python executable that came with the operating system - they will not accidentally run the version of Python that came with Anaconda. At the end of the day you can simply install Anaconda without worrying about any of these details.
+对Linux和Mac用户而说,你的系统很有可能已经安装了某个版本的Python。*千万不要尝试卸载,删除,或修改系统自带的Python*。这些操作系统用它们自带的Python去执行系统的一些服务。这些服务会直接专门调用系统自带的Python可执行文件——它们不会意外地使用Anaconda版本的Python。所以你要知道的就是你可以安装Anaconda而不担心以上这些细节。
-**An important note for people who code in languages other than Python:** Anaconda has its own `lib` and `bin` directories that it uses to store library files and binary files as needed. While this makes it very easy for users to install sophisticated Python packages that leverage C-libraries without having to manually build those libraries, it also means that your system will prioritize Anaconda's files before your system-level files. This can be a big problem if you work in languages other than Python.
+**对用其它编程语言写代码的人的重要事项:**Anaconda使用它自己的 `lib` 和 `bin` 文件夹来存储模组文件和二进制文件。虽然这让用户可以简单地安装复杂的使用C库的Python模组,但是这也意味着你的系统会首先使用Anaconda的文件而不是你的系统的 `lib` 和 `bin`。如果你编写其它语言的代码,这可能会是个大问题。
-The simple solution to this is to *not* have the Anaconda-installer include Anaconda in your path. Instead, you can create an alias that will allow you manually prepend Anaconda to your path. E.g., in Linux you can add the following alias to your `~/.bashrc` file:
+最简单的解决方案就是*不要*让Anaconda安装器将Anaconda包含在你的path里面。你可以创建一行alias(代名)来手动前置Anaconda到你的path里。比如说,在Linux上你可以在 `~/.bashrc` 文件中添加如下的alias:
```shell
alias anaconda="export PATH=/home//anaconda3/bin:$PATH"
```
-With this alias in place, you can simply invoke the command `anaconda` in your terminal to place Anaconda at the beginning of your path for that terminal session.
+设置好这个alias后,你可以从命令台调用 `anaconda` 来将Anaconda暂时添加到path的顶端——这只维持到你当前命令台被关闭之前。
-### A Brief Introduction to Conda Environments
+### 快速入门Conda环境
-`conda` is not only a package manager, but also a powerful environment manager. Let's take a moment to motivate a common use case for environment management before we dive into what it actually is:
+`conda` 不仅仅是一个包管理器,它也同时是一个很强大的环境管理器。在了解它之前,让我们先看看为什么我们会需要一个环境管理器:
->It is expected and encouraged that you work through Python Like You Mean It using the latest version of Python (Python 3.X). That being said, it is not uncommon to encounter courses and projects that require you to use Python 2.7, which is a dead version of the language. Is there a simple and sane way to switch back and forth between working in Python 3 and Python 2.7 environments? Yes! Utilizing conda environments is a perfect way to solve this problem.
+>PLYMI建议你使用最新版本的Python(Python 3.X)来阅读本资源。但是,很多时候其它的课程或项目会需要你使用Python 2.7,一个已经不被更新或维护的Python版本。有没有一个简单干净的方法来快速在Python 3和Python2.7环境中切换呢?有!使用conda环境可以完美解决这个问题。
-Assuming that your initial installation of Anaconda contained Python 3, then your *root* (i.e. default) conda environment is that Python 3 environment. You can now create a conda environment that instead includes Python 2.7 and all of the 3rd party packages that come with Anaconda. Execute the following command in your terminal:
+假设你的Anaconda安装包含了Python 3,那你的*root*(默认)conda环境就是这个Python 3环境。你现在可以创建一个包含Python 2.7和所有Anaconda自带的第三方模组的conda环境。在你的命令行中执行以下指令:
```shell
conda create -n py27 python=2.7 anaconda
```
-Once the installation process is complete, you will be able to activate this environment, which we have named `py27`, by executing the command (Linux, Mac):
-```shell
-source activate py27
-```
-in your terminal. If you are in Windows, the command is:
+当安装成功后,你将可以激活(activate)这个叫做 `py27` 的环境。在命令行中执行以下命令:
```shell
-activate py27
+conda activate py27
```
-Activating an environment simply updates your system's path, swapping the directory `Anaconda3` with `Anaconda3/envs/py27` in this instance. Thus your system will now find the Python 2.7 executable and its associated libraries in its path. Note that this path change only occurs effect in *that particular terminal session*. Any other terminal session will default to the root conda environment.
-Having activated your `py27` environment, you can start a vanilla Python console, an iPython console, a Jupyter notebook, run a Python script, etc. These will now all use Python 2.7. You can also use `conda` (and `pip`) to install Python 2.7-compatible packages in this environment. As long as your path points to `Anaconda3/envs/py27` and not `Anaconda3`, it is as if this is the only version of Python that lives on your computer.
+激活一个环境仅仅会更新你的系统path变量。在本例中这意味着 `Anaconda3` 会被更新为 `Anacond3/envs/py27`。这样你的系统就会在path中找到Python 2.7的可执行文件还有该版本相对应的模组。请注意这个变化仅仅作用于**当前的命令行进程**。任何其它的命令行进程都会默认使用叫做root的conda环境。
-Deactivating this environment will return you to the root Python 3 environment. That is, it will switch your path back to including `Anaconda3` instead of `Anaconda3/envs/py27`. Simply invoke the command (Mac, Linux):
-
-```shell
-source deactivate
-```
+当你激活名为 `py27` 的环境后,你可以使用Python命令行,iPython命令行,Jupyter记事本,执行Python脚本,等等。这些现在都会使用Python 2.7。你可以用 `conda`(和 `pip`)来在这个环境中安装和Python2.7兼容的模组。只要你的path指向的是 `Anaconda3/envs/py27` 而不是 `Anaconda3`,这些指令的行为就会如同Python 2.7是计算机上唯一的Python版本一般。
-On Windows, the command is:
+冻结(`deactivate`)这个环境将将你返回到名为root的Python 3环境。这意味着conda将重新修改path,让它包含 `Anaconda3` 而不是 `Anaconda3/envs/py27`。执行以下指令:
```shell
-deactivate
+conda deactivate
```
-And like that, conda environments give you all of the powers of a necromancer, allowing you to nimbly cross back and forth between the land of the living (Python 3) and the dead (Python 2.7).
+就这样,conda环境提供给你像招魂师一样的能力,轻便地在活的(Python 3)和死的(Python 2.7)之间切换。
-Conda environments have more uses than simply switching back and forth between Python 3 and 2. Many people like to make a new conda environment for every major project that they work on, so that they can freely install any dependencies that are needed for that particular project, without worrying about conflicts with their other work. You should be keen on making regular use of conda environments.
+除了在Python 3和2之间切换,conda环境有着很多其它的作用。很多人喜欢为每一个新的大规模项目创建一个新的conda环境。这样他们可以随意安装任何该项目需要的模组而不用担心和其他项目模组的冲突。读者应当注意学习和使用conda环境。
-It is highly recommended that you take time to read through [this tutorial on managing conda environments](https://conda.io/docs/user-guide/tasks/manage-environments.html).
-
+我非常建议你去阅读[这个管理conda环境的教程](https://conda.io/docs/user-guide/tasks/manage-environments.html)。译者注:同样是英文的文档,可以考虑不看。
diff --git a/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md b/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md
index 9b63e96..915be5f 100644
--- a/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md
+++ b/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md
@@ -4,92 +4,99 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Jupyter notebooks, Difficulty: Easy, Category: Tutorial
- :keywords: jupyter, notebook, kernel, basics, server, console, command line, plot, beginner, data science
-```
+ :keywords: jupyter, jupyter lab, notebook, kernel, basics, server, console, plot, beginner, data science
+
+
+# Jupyter记事本
+近年来,Jupyter Notebook(记事本)成为了一个极其流行的帮助用户使用Python和其它语言做实验的工具。它的流行代表着数据科学实验形式的转变。
+
+Jupyter记事本类似于IPython命令行,但,相比起IPython每次编写运行一行代码的形式,你可以轻松地编辑和重新执行*任何*在记事本中的代码。同时,你可以保存一个记事本,然后在未来去运行和修改它。Jupyter记事本提供很多特别实用的功能。比如说,你可以在记事本中嵌入可视化的多媒体(如表格和图画)并利用[Markdown语法](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)编写方便美观的文本来演示和解释记事本的内容。
-# Jupyter Notebooks
-In recent years, the Jupyter Notebook has become a massively popular tool for doing research-oriented work in Python and other languages alike. Its emergence marked a paradigm shift in the way data science is conducted.
+通过以上这些方式,Jupyter记事本成为了一个出众的实际应用工具。比如说,你可以在一个记事本上跟随本文的流程,边读边运行本文的代码片段和回答阅读理解问题,并同时使用Markdown标题来视觉上区分记事本的不同区块。当我做研究时,我经常创建Jupyter记事本以编写代码来分析数据,绘制各种实验结果的图表,并撰写详细的Markdown文本来记录我的工作。最后产生的成果是一个我可以分享给我同事的记事本。我可以在几个月后重新打开这个记事本而不会不记得我之前都做了些什么。
-A Jupyter notebook is similar to the IPython console, but, instead of only being able to work with a single line of code at a time, you can easily edit and re-execute *any* code that had been written in a notebook. Furthermore, you can save a notebook, and thus return to it later. Additionally, a notebook provides many terrific features. For instance, you can embed visualizations of data within a notebook, and write blocks of nicely-formatted text (using the [Markdown syntax](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)), for presenting and explaining the contents of the notebook.
+## JupyterLab
-In this way, the Jupyter Notebook stands out as an excellent tool for many practical applications. You could work on a notebook while you are working through sections of this website, for instance, testing out snippets of code, and answering reading-comprehension questions as you proceed through the text, and using markdown-headers to visually separate different portions of the notebook. When I do research, I am always creating Jupyter notebooks in which I write code that analyzes data, I plot various results, presented in different ways, and I write detailed markdown-text blocks to document my work. The end result is something that I can share with my labmates, and easily revisit months later without having to struggle to recall what I had done.
+[JupyterLab](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)是由Project Jupyter团队开发的一个全新的网页端交互界面。通过它,你可以在你的浏览器中编辑并运行Jupyter记事本,命令行,和文本编辑器。除了各种功能和相比Jupyter记事本更加成熟的用户界面之外,JupyterLab还提供了可以用来显示数据,图片,和代码输出的在Jupyter记事本之外的可移动窗口。这将允许你高效地进行数据科学工作。
-Enough gushing about Jupyter notebooks. Let's start using them!
+本文在这里推荐你阅读[JupyterLab说明文档](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)来了解它提供的额外功能。
+下文将针对Jupyter记事本来进行讨论,但是运行JupyterLab服务器和操作其中的记事本的方法和Jupyter记事本基本完全一样。Jupyter记事本和JupyterLab都可以[用Anaconda安装](https://cn.pythonlikeyoumeanit.com/Module1_GettingStartedWithPython/Installing_Python.html)。
-## Running a Notebook Server & Creating a Notebook
-In your terminal, navigate to a directory (a.k.a folder) that you are okay creating files in. If you don't know how to do this, Google it!
+## 运行记事本服务器并创建记事本
+废话不多说,让我们来使用Jupyter记事本吧!
-Once you are in the desired directory, execute in your terminal (type the following, and then hit ``): `jupyter notebook`
+在你的命令行中,导航到随便一个你愿意创建文件的文件夹。如果你不知道怎么做,上网搜一下!
-You should see some text appear in your terminal:
+当你的命令行在你想要的文件夹内后,运行(键入以下内容然后回车):`jupyter notebook`
+
+你应该会看到以下的内容出现在你的命令行中:

-This is a "notebook server" that is running on your machine - it basically handles all of the communication between your browser and your machine. A new window or tab should open in your web browser, which looks like a file explorer.
+这是一个在你机器上运行的“记事本服务器”——它将会处理所有在你浏览器和机器之间的交互。一个看起来像文件夹浏览器的窗口应该会在你的浏览器中打开。

-You can use this to enter subdirectories and to open up any Jupyter notebooks that you have saved. *You will need to use this file explorer any time that you want to open up a Jupyter notebook, old or new.* In the top-right corner of this window, click on the dropdown menu labeled "New", and select the option `Python 3`.
+你可以利用这个界面进入子文件夹并打开任何已经存储的Jupyter记事本。*不管是新是旧,每次你想要打开一个Jupyter记事本时你都需要使用这个文件夹浏览窗口。*在窗口右上角,你可以点击展开菜单“New”并选择选项 `Python 3`。

-A new tab will open in your browser, revealing a "Jupyter notebook" called `Untitled.ipynb` running a Python 3 kernel. Clicking `File > Rename` in the notebook will enable you to name your notebook. `.ipynb` is the file-type suffix used for Jupyter notebooks (`ipynb` stands for "IPython-notebook", which is what these notebooks were called prior to 2014). The commands that you run in this notebook are interpreted and executed by Python in the essentially same way that they would be in a IPython console.
+你的浏览器会打开一个新的窗口并显示一个名为 `Untitled.ipynb` 的运行Python 3壳的Jupyter文件夹。点击 `File > Rename` (文件 > 重命名)会允许你修改记事本的名字。`.ipynb` 则是Jupyter记事本的文件类型后缀(`ipynb` 代表着 "IPython-notebook",也就是这些Jupyter记事本在2014年前的名字)。在这个记事本中运行的命令会被Python像IPython命令输入行一样直译并执行。
-**Jupyter Notebooks Do Not Use the Internet**:
+**Jupyter记事本并不使用互联网**:
-Although a Jupyter notebook opens in your browser, *everything is happening locally on your machine*. You don't need to be connected to the internet to work on a Jupyter notebook! The notebook server that you ran in your terminal is simply routing communication from your browser to your local machine. For instance, it is sending code to your CPython interpreter to be executed.
+虽然Jupyter记事本在你的浏览器中打开,*所有的东西都是在本地机器上发生的*。你不需要连接互联网来使用Jupyter记事本!在命令行中运行的记事本服务器仅仅管理浏览器和本地机器的交互。比如说,它会将代码发送到你的CPython直译器去运行。
-## Notebook Cells
-Whereas a Python console only allows you to work on one line of code at a time, a notebook allows you to write code within "cells" and to execute these chunks of code cell-by-cell. In the first cell, write the lines of code:
+## 记事本小节
+在Python命令行中,你每次只能编写一行代码;但一个记事本让你可以以小节(cell)为单位来编写和运行代码。在你的记事本的第一小节中,输入以下代码:
```python
x = 3
y = 4
```
-then press `+`. This will execute all of the code within the given cell (in this instance, assigning the variables `x` and `y` with the values 3 and 4, respectively) and then creates a new cell below. In the next cell type the code:
+然后敲击 `+`。这会运行这个小节里的所有代码(在这个例子中,这会分别给 `x` 和 `y` 赋值 3 和 4)并在下面创建一个新的小姐。在新的小节中输入以下代码:
```python
x + y
```
-and hit `+` to execute this code. The number 7 will appear beneath the cell - this, of course, is the value that is returned when `3 + 4` is evaluated:
+敲击 `+` 以运行此代码。小节下面会显示数字 7——也就是运行 `3 + 4` 的结果:

-Notice that the notebook "knows" about its variables across its cells. This doesn't just work from top to bottom - you can define `z = 2` in the third cell, and then execute code that references `z` in the first cell. What really matters is the *order* in which the cells are executed. Notice that `In[1]` denotes that the top cell with the first input-cell executed in the notebook, and `In[2]` denotes the second cell that was executed.
+请注意,记事本“知道”在不同小节中的变量。这不仅仅在从上到下时适用——你可以在第三小节定义 `z = 2`,然后在第一小节运行调用 `z` 的代码。唯一需要注意的是运行这些小节的*顺序*。注意 `In[1]` 代表这个小节是第一个在这个记事本中被执行过的小节,而 `In[2]` 代表着第二个被执行过的小节。
-Formally, the cells within a given notebook share a common "namespace": any variable defined in a cell can be referenced or redefined in any other cell within the notebook. On the other hand, separate notebooks are completely independent from one another. You can be working on multiple notebooks at once, and they will never "know" about one another.
+正式来讲,在一个记事本中的所有小节共享同一个“命名空间”(namespace):在任何一个小节中定义的变量可以在任何其它相同记事本的小节中调用或重新定义,但但不同的记事本的命名空间互相完全独立。也就是说你可以同时编写多个记事本,而它们永远也不会“知道”互相的存在。
-A major value of using a notebook is that you can rapidly edit these cells (say, change `x = 3` to `x = 10`), and re-execute them to nimbly tinker with whatever code you are developing. Although simple, this is a hugely powerful environment for prototyping code.
+使用记事本的一大好处是你可以快速地修改这些小节(比如将 `x = 3` 改成 `x = 10`)并重新执行它们来尝试你正在编写的新代码。这是一个简单却极其强大的编写新代码的环境。
-## An Example Notebook
-To show off a more exciting use-case, let's create a notebook that plots some data for us. We'll use matplotlib, a Python library that is used for plotting data, and NumPy, the premiere library for doing numerical work in Python. We will import these libraries for use in our code. Next we'll define some mathematical functions. And finally, we'll plot these functions evaluated on a large number of closely-spaced points on the domain.
+## 样例记事本
+为了演示一个更加有趣的记事本使用情景,让我们创建记事本来绘制一些数据图。我们将使用matplotlib,一个用于绘制数据的Python模组,和NumPy,旗舰的数字工作Python模组。我们将导入这些模组。然后,我们将定义一些数学函数。最后,我们将绘制这些函数在大量数值上的解。
```python
import numpy as np
import matplotlib.pyplot as plt
-# this tells Jupyter to embed matplotlib plots in the notebook
+# 这会告诉Jupyter将matplotlib的图表嵌入在记事本中
%matplotlib notebook
```
@@ -98,19 +105,19 @@ def sinc(x):
return np.sin(x) / x
def d_sinc(x):
- "derivative of sinc-function"
+ "sinc函数的导数"
return np.cos(x)/x - np.sin(x)/x**2
```
```python
-# evaluate functions at 1000 points evenly spaced in [-15, 15]
+# 用1000个平均分布在[-15, 15]之间的点求值
x = np.linspace(-15, 15, 1000)
f = sinc(x)
df = d_sinc(x)
```
```python
-# plot the sinc-function and its derivative
+# 绘制sinc函数和它的导数
fig, ax = plt.subplots()
ax.plot(x, f, color="red", label=r"$sinc(x)$")
ax.plot(x, df, color="blue", ls="--", label=r"$\frac{d(sinc(x))}{dx}$")
@@ -123,48 +130,47 @@ ax.grid(True)
ax.legend();
```
-Notice that this notebook interface is great for making adjustments to this plot. You can easily change the color or line-style of the plot and redraw it without having to recompute the functions. You simply re-execute the cell containing the plot code. This is especially nice when the numerical computations required to generate the curves are costly.
+注意这个记事本界面很方便对图表做修改。你可以轻松地修改图表的颜色或线条风格并重新绘制,而不需要重新计算这些函数的解。你可以直接重新执行含有绘图代码的小节。这在计算要绘图的数据很昂贵时极其有用。
-## Familiarizing Yourself with Jupyter Notebooks
-Here, we will review some essential keyboard shortcuts and notebook features, which will enable you to use notebooks competently. A notebook has two modes of operation:
+## 熟悉Jupyter记事本
+在这一段,我们会列出常用的键盘快捷键和记事本功能来帮助你有效地使用记事本。一个记事本有两种不同的模式:
-**Command Mode (Press** `` **to activate)**
+**命令模式 (敲击** `` **来激活)**
-When in command mode, you can use keyboard shortcuts to create/delete/cut/paste notebook cells, and to change a cell's type between code and markdown modes. Your selected cell will be surrounded by a *blue* border when you are in command mode. For a complete listing of keyboard shortcuts, toward the top of the notebook click `Help > Keyboard Shortcuts`. The most critical shortcuts are:
+在命令模式中,你可以使用键盘快捷键来创建/删除/剪接/粘贴记事本小节或更改小节的类型(如代码或Markdown)。当你在命令模式中,你选择的小节会有一个*蓝色*的边框。你可以点击记事本上方的 `Help > Keyboard Shortcuts` (帮助 > 键盘快捷键)来查看所有的快捷键。最重要的快捷键是:
-- create a new cell above the current cell: `a`
-- create a new cell below the current cell: `b`
-- delete the current cell: `dd`
-- restart the notebook kernel (kill all executions and erase all defined variables): `00`
-- change the current cell's type to "Code": `y`
-- change the current cell's type to "Markdown": `m`
+- 在当前小节上方创建一个新的小节:`a`
+- 在当前小节下方创建一个新的小节:`b`
+- 删除当前小节:`dd`
+- 重启记事本壳(杀死所有进程并删除所有定义的变量):`00`
+- 将当前小节的类型改为“代码”:`y`
+- 将当前小节的类型改为“Markdown”:`m`
-**Edit Mode (Press** `` **to activate)**
+**编辑模式(敲击** `` **来激活)**
-Edit mode simply permits you to type text into the selected cell. When in edit mode, the current cell will be surrounded by a *green* border. There are two commands for executing a cell:
+编辑模式允许你去在选择的小节中输入文本。在编辑模式中,当前选择的小节会有一个*绿色*边框。记事本提供两个执行小节的命令:
-- execute current cell: `+`
-- execute current cell and then create a new cell below: `+`
+- 执行当前小节:`+`
+- 执行当前小节并在下方创建新小节:`+`
-By default, a cell will be a code-type cell, meaning that its content will be formatted and executed as Python code. Just as you saw when using the IPython notebook, `` can be used to perform autocomplete. Additionally, when your cursor is on the name of a Python function in your code, `+` will bring up a small window with the function's documentations string. This is *very* useful.
+小节在创建时默认为代码小节,意味着它的内容会被当作Python代码格式化和执行。就如IPython命令台一样,`` 可以用来自动完成代码。同时,当你的光标在代码中某个Python函数名字上方时,`+` 将打开一个包含该函数的说明字符串的小窗口。这将*很*有用。

-### Markdown Cells
-When a cell is set to Markdown type, its content will not be interpreted as Python code. Instead, its contents will be rendered as stylized text. Refer to [this page](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) as a reference for various markdown stylings. Using markdown cells allows you to create section and subsection headers for your notebook, you can [render LaTeX math equations](http://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations), embed images and videos in your notebook, and much more. In fact, every page in this website was created using Jupyter notebooks! Markdown-type cells are tremendously useful for creating high-quality, well-documented Jupyter notebooks. These are perfect for lab-report assignments.
+### Markdown小节
+当一个小节被设置为Markdown类型时,它的内容不会被当成Python代码,反而会被渲染成风格化的文本。参考[此页](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)来学习如何使用不同的Markdown语法。使用Markdown小节会允许你在记事本中创建章节和字章节标题。你可以[渲染LaTeX数学公式](http://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations),在记事本中嵌入照片和视屏,以及更多。事实上,这个网站的每一页都是用Jupyter记事本创建的!Markdown类型的小节对创建高质量,详细记录的Jupyter文件夹极其有用。它们可以完美应对实验汇报类的作业。
-**Be Aware of Cell-Type**:
+**注意小节类型**:
-If you ever find that your Python code isn't being formatted properly, and doesn't run at all when you execute the cell (you get no output, not even errors), there is a good chance that you have accidentally set the cell to be a 'Markdown'-type cell! Change the cell back to code-type by entering command mode (``) and pressing `y`.
+如果你发现你的Python代码没有被正确地格式化,且在执行小节时根本不运行(你看不到任何输入或者错误),那很有可能你一不小心将小节设置为了Markdown类型!进入命令模式(``)并敲击 `y` 以将小节改回代码类型。
-
-### Using Jupyter Notebooks with Other Languages
-The Jupyter Notebook does not work exclusively with Python. A "kernel" can be developed in order to provide support for a given programming language in Jupyter. Indeed, kernels for several prominent programming languages are being developed for use with Jupyter:
+### 将Jupyter记事本用于其它语言
+Jupyter记事本不只支持Python。你可以在Jupyter中为任何编程语言开发一个“壳”(Kernel)。其实很多重要的编程语言都有着自己相对应的壳:
- [R](https://github.com/IRkernel/IRkernel)
- [Julia](https://github.com/JuliaLang/IJulia.jl)
@@ -173,5 +179,7 @@ The Jupyter Notebook does not work exclusively with Python. A "kernel" can be de
- [Haskell](https://github.com/gibiansky/IHaskell)
- [Go](https://github.com/gopherdata/gophernotes)
-The ever-growing list of available kernels for use with Jupyter can be found [here](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels). It should be noted that these efforts are not all equally mature. For instance, whereas the Python and Julia kernels are robust, the Haskell kernel cannot run natively on Windows machines, and the C++ kernel is still in early development, as of writing this.
+这时刻增长的可用Jupyter壳列表在[这里](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels)列出。请注意并不是所有的这些项目都很成熟。比如说,虽然Python和Julia的壳都比较强健,Haskell的壳不能在Windows机器上本地化运行,而C++的壳在编写本文时还在前期开发中。
+### Visual Studio Code的Jupyter记事本支持
+Visual Studio Code在近期[开始官方支持Jupyter记事本](https://devblogs.microsoft.com/python/announcing-support-for-native-editing-of-jupyter-notebooks-in-vs-code/)。这意味着你可以在[Visual Studio Code IDE](https://cn.pythonlikeyoumeanit.com/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.html)中直接编辑Jupyter记事本,并可以享受如代码完成,调试,和查看变量的额外功能。
\ No newline at end of file
diff --git a/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md b/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md
index 5ec2450..b98fb0a 100644
--- a/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md
+++ b/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md
@@ -4,8 +4,8 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
diff --git a/Python/Module1_GettingStartedWithPython/SiteFormatting.md b/Python/Module1_GettingStartedWithPython/SiteFormatting.md
index f5f71a4..bdaadb3 100644
--- a/Python/Module1_GettingStartedWithPython/SiteFormatting.md
+++ b/Python/Module1_GettingStartedWithPython/SiteFormatting.md
@@ -4,67 +4,68 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Overview of formatting in Python Like You Mean It, Difficulty: Easy, Category: Instructions
:keywords: overview, formatting, background, code block, console style
-```
+
-# A Quick Guide to Formatting
-This section provides a brief overview of the code formatting style that will be used throughout this text. You are not expected to understand the details of the code, here. This merely provides a guide for what is to come.
+# 代码格式的简单指南
+本节将快速介绍本文将采用的代码格式和风格。你暂时不需要理解这些代码的具体细节。这个指南仅仅是为了让你了解接下来的内容的样貌。
-Any code that is included in-line within plain text will be formatted distinctly as so: "the variable `x` was updated...". Such items will be distinguished with backticks wherever such formatting is not available. Take for example the following commented line within Python code:
+任何嵌入在正文中的代码都会遵循如此格式:“变量 `x` 被更新...”。当这种格式不可用时,这类小代码片段会被两个反引号围绕。如下:
```python
-# the variable `x` will be updated
+# 变量 `x` 将被更新
```
-Python code will be displayed within distinct, colorized code blocks. These will typically begin with a comment, which is meant to serve as a caption that summarizes the purpose of the code block:
+长篇的Python代码则会存在于专门的彩色代码块中。这些代码块一般会由一行总结代码块作用的注解打头:
```python
-# demonstrating a basic for-loop
+# 演示基本的for循环
cnt = 0
for i in range(10):
cnt += 1
-#`cnt` is now 10
+# `cnt` 现在是10
```
-The symbol `>>>` appears within code blocks to indicate "console-style" code, which distinguishes between code being entered by a user and the resulting output. The purpose of this is that it allows us to easily display the result of a computation without having to rely on calling the `print` function. For instance, the following code assigns the integer `1` to the variable `x`, and then displays the result of `x + 2`:
+符号 `>>>` 出现于“命令行风格”的代码中,用于区分用户输入的代码和命令行的输出。这类代码块的可以帮助我们轻松地显示计算结果,而不需要老是调用 `print` 函数。比如说,接下来的代码将设定变量 `x` 为整数 `1`,然后显示 `x + 2` 的结果:
```python
-# demonstrating the distinction of
-# input and output via >>>
+# 通过 >>> 演示输入和输出的不同格式
>>> x = 1
>>> x + 2
3
```
-The code blocks throughout a given section of the text should be understood to be persistent even if there is a mix of "pure" code blocks and "console-style" code blocks. For example, a function may be defined at the beginning of a section, and then referenced throughout the rest of that section:
+译者注:命令行在这里泛指各大平台上的类似Windows命令行的程序——你可能会叫它们Git Bash,Terminal,命令行,Shell,Kernel,等等。全文将用“命令台”一词来指代这种程序。
+
+不管是“纯粹”的代码块还是“命令行风格”的代码块,请在章节内认为它们的效应是持久化的。比如说,在某一节开始定义的函数完全在这一节后面被调用:
```python
-# defining an example function
+# 定义一个范例函数
def my_func(x):
return x**2
```
-We can spend some time talking about `my_func` and then see it in action:
+我们可以花些时间讨论 `my_func` 并调用它:
```python
-# demonstrating `my_func`
+# 演示 `my_func`
>>> my_func(10.)
100.
```
-Lastly, the input and output of an iPython console and a Jupyter notebook alike is displayed as follows:
+最后,iPython命令台和Jupyter记事本的输入和输出都像如下显示:
```python
diff --git a/Python/Module2_EssentialsOfPython/Basic_Objects.md b/Python/Module2_EssentialsOfPython/Basic_Objects.md
index 486a285..ca7d291 100644
--- a/Python/Module2_EssentialsOfPython/Basic_Objects.md
+++ b/Python/Module2_EssentialsOfPython/Basic_Objects.md
@@ -4,105 +4,105 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Basics of Python Objects, Difficulty: Easy, Category: Section
:keywords: integers, booleans, floats, floating point precision, lists, strings, fundamentals
-```
+
-# Basic Object Types
+# 基本对象类型
-**Note**:
+**注**:
-There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.
+在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-You will see the term "object" be used frequently throughout this text. In Python, the term "object" is quite the catch-all; including numbers, strings of characters, lists, functions - a Python object is essentially anything that you can assign to a variable. That being said, there are different *types* of objects: Python treats integers as a different *type* of object than a string, for instance.
+本文会经常使用“对象”这一单词。在Python中,“对象”包含了很多东西:数字,字符串,列表,函数,等等。简单来讲,一个Python对象是任何可以赋值给变量的东西。尽管如此,对象是分*类型*(type)的:比如说在Python眼中,整数(integer)和字符串(string)的*类型*是不一样的。
-The different object types have manifestly different purposes and thus have different built-in functions available to them. Here, we will review some of the basic types that are built into Python, as a natural entry point to writing code. We will cover:
+不同类型的对象为了不同目的而存在,而因此也有着不同的内置函数。在这里,我们将复习Python自带的一些基本类型并以此写一些代码。我们将会讨论:
-- numbers (integers, floating-point numbers, and complex numbers)
-- booleans
-- the "null" type
-- strings
-- lists
+- 数字(整数,浮点数,复数)(number(integer,float-point number,complex number))
+- 布尔值(真或否)(boolean)
+- “空”值类(the "null" type)
+- 字符串(string)
+- 列表(list)
-The built-in function `isinstance` will allow us to check if an object is of a given type. You can also use the built-in `type` function to check an object's type. For example, the following code checks if an object is an integer:
+Python自带的 `isinstance` 函数允许我们检测对象是否为某一类型。你也可以用自带的 `type` 函数来查看对象的类型。比如说,下面的代码会检测一个对象是否是整数:
```python
-# assign the variable `x` to the integer 1
+# 对变量 `x` 赋值整数 1
>>> x = 1
-# checking the type of `x`
+# 查看 `x` 的类型
>>> type(x)
int
-# verifying that `x` is an integer-type object
+# 检测 `x` 是否是整数类(integer)
>>> isinstance(x, int)
True
```
-In a later module, you will learn "object-oriented" programming, which will allow you to create your own, customized objects!
+在之后的模组中,你将学习“面对对象”的编程模式。这将允许你创建你自己的定制对象种类!
-## Number Types
-Python has three basic types of numbers: integers, "floating-point" numbers, and complex numbers. Familiar mathematical symbols can be used to perform arithmetic on all of these numbers (comparison operators like "greater than" are not defined for complex numbers):
-
-| Operation | Description |
-| ------------- |:-------------:|
-| `x + y` | Sum of two numbers |
-| `x - y` | Difference of two numbers |
-| `x * y` | Product of two numbers |
-| `x / y` | Quotient of two numbers |
-| `x // y` | Quotient of two numbers, returned as an integer |
-| `x % y` | `x` "modulo": `y`: The remainder of `x / y` |
-| `x ** y` | `x` raised to the power `y` |
-| `-x` | A negated number |
-| `abs(x)` | The absolute value of a number |
-| `x == y` | Check if two numbers have the same value |
-| `x != y` | Check if two numbers have different values |
-| `x > y` | Check if `x` is greater than `y` |
-| `x >= y` | Check if `x` is greater than or equal to `y` |
-| `x < y` | Check if `x` is less than `y` |
-| `x <= y` | Check if `x` is less than or equal to `y` |
-
-These operations obey the familiar order of operations from your mathematics class, with parentheses available for association:
-
-```python
-# multiplication takes precedence over addition
+## 数字类型
+Python有三种基本的数字类型:整数(integer),浮点数(floating-point number),和复数(complex number)。你可以使用你熟悉的数学运算符来对这三种数字进行算术操作(像“大于”这种比较性的运算符没有定义如何处理复数):
+
+| 操作 | 描述 |
+| ---- |:----:|
+| `x + y` | 求两数相加的结果 |
+| `x - y` | 求两数相减的结果 |
+| `x * y` | 求两数相乘的结果 |
+| `x / y` | 求两数相除的结果 |
+| `x // y` | 求两数相除的整数商 |
+| `x % y` | 求两数的模(`x` modulo: `y`,也就是 `x / y` 的余数)|
+| `x ** y` | 求 `x` 的幂 `y` |
+| `-x` | 求负数 |
+| `abs(x)` | 求数的绝对值 |
+| `x == y` | 检测两数是否等值 |
+| `x != y` | 检测两数是否不等值 |
+| `x > y` | 检测 `x` 是否大于 `y` |
+| `x >= y` | 检测 `x` 是否大于或等于 `y` |
+| `x < y` | 检测 `x` 是否小于 `y` |
+| `x <= y` | 检测 `x` 是否小于或等于 `y` |
+
+这些运算符和你平时在数学课上见到的运算顺序一样,在没有括号的情况下遵循先乘除后加减。
+
+```python
+# 先乘除后加减
>>> 1 + 2 * 3
7
-# grouping operations with parentheses
+# 用括号更改运算顺序
>>> (1 + 2) * 3
9
-# finding the remainder of division
+# 求余数
>>> 11 % 5
1
-# checking an inequality
+# 检测不等式是否成立
>>> (2 ** 3) < (2 ** 4)
True
```
-It should be noted that in many other programming languages, including the out-dated Python 2, dividing two integers would always return an integer - even if mathematically the result should be a fraction. In Python 3, *the quotient of two integers will always return a floating-point number* (i.e. a number that includes a decimal point):
+请注意:在很多其他的编程语言中(包括Python 2),两个整数相除永远都会返回一个整数——就算数学上的结果应该是个分数。在Python 3中,*两个整数相除永远都会返回一个浮点数*(一个包含小数点的数字):
```python
-# In many other languages, 3 / 2 returns the integer 1.
-# In Python 3, division always returns a floating-point number:
+# 在很多别的语言中,3 / 2 会返回整数 1
+# 在Python 3中,除法返回一个浮点数
>>> 3 / 2
1.5
@@ -110,10 +110,10 @@ It should be noted that in many other programming languages, including the out-d
2.0
```
-The `//` operator is known as the "floor-divide" operator: it performs division between two numbers and returns the result as an integer by discarding any decimal-places for that number (thus returning the "floor" of that number). This can be used to perform the integer-division traditionally used in other programming languages:
+运算符 `//` 英文叫做“floor-divide”(直译“地板除”):它取两数相除之后去尾(去掉浮点数小数点后的数字)得到的整数(因为浮点数取整可以往上入——4.5入到5——或者往下舍——4.5舍到4——,所以去尾被称为地板除)。这可以用来进行很多其他语言中传统的整数相除:
```python
-# floor-division
+# “地板除“
>>> 1 // 3 # 0.3333.. -> 0
0
>>> 3 // 2 # 1.5 -> 1
@@ -123,14 +123,14 @@ The `//` operator is known as the "floor-divide" operator: it performs division
-**Reading Comprehension: Understanding the modulo operator**
+**阅读理解:理解模运算符**
-The modulo operator, `%`, is not commonly seen in mathematics textbooks. It is, however, a very useful operation to have at our disposal. `x % y` (said as x "mod" y in programmer's jargon) returns the *remainder* of `x / y`. For example:
+模运算符 `%` 在数学教材中并不常见。但是它在我们手中是很有用的一个运算符。`x % y` (读作 x “模”(mod)y)返回 `x / y` 的余数。比如说:
-- $\frac{3}{2} = 1 + \frac{1}{2}$. 2 "goes into" 3 one time, leaving a remainder of 1. Thus `3 % 2` returns `1`
-- $\frac{9}{3} = 3$. 3 "goes into" 9 three times, and leaves no remainder. Thus `9 % 3` returns `0`
+- $\frac{3}{2} = 1 + \frac{1}{2}$. 3 中可以去除一个 2,最后余下 1,所以 `3 % 2` 返回 `1`
+- $\frac{9}{3} = 3$. 9 中可以去除三个 3,什么都不余下。所以 `9 % 3` 返回 `0`
-Given this description of the "mod" operator, simplify the following by hand, and then use the IPython console to check your work:
+根据以上对模运算符的解释,先自己猜测下方表达式的结果,并用IPython命令行检查你的答案:
1. `1 % 5`
2. `2 % 5`
@@ -141,22 +141,21 @@ Given this description of the "mod" operator, simplify the following by hand, an
7. `22 % 5`
6. `22 % 6`
-Now, given any integer, `n`, what are the possible values that `n % 2` can return? See if you can come up with a simple rule for explaining the behavior of `n % 2`.
+假设 `n` 是任何整数,`n % 2` 可能返回哪些数值?尝试简明地解释 `n % 2` 的行为。
-### Python's math module
-The standard library's math module provides us with many more mathematical functions, like logarithms and trigonometric functions. A complete listing of them [can be found in the official Python documentation](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions). This module must be imported into your code in order to use its functions:
+### Python的math模组
+标准库的math模组为我们提供更多的数学函数,像对数(logarithm)和三角函数。完整的列表[可以在Python官网上找到](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions)。要使用math模组里的函数,你必须先导入它。
```python
-# using the `math` module to use
-# additional mathematical functions
+# 使用 `math` 模组里面的数学函数
>>> import math
>>> math.sqrt(4.)
2.0
-# base-10 log
+# 以10为底的对数
>>> math.log10(10.)
1.0
@@ -167,46 +166,46 @@ The standard library's math module provides us with many more mathematical funct
-### Integers
-As in traditional mathematics, an integer is any "whole" number: $\dots, -3, -2, -1, 0, 1, 2, 3, \dots$.
+### 整数
+像传统数学一样,一个整数是任何没有小数点的数字:$\dots, -3, -2, -1, 0, 1, 2, 3, \dots$。
-Integers belong to the built-in type `int`, which can be used to convert objects to integers:
+整数属于内置类 `int`,而 `int` 则可以用来将其它对象转化成整数:
```python
>>> type(-3)
int
-# `1.3` is not an integer-type object
+# `1.3` 不是整数对象
>>> isinstance(1.3, int)
False
-# converting a string to an integer
+# 将字符串转化成整数
>>> int("10")
10
-# converting a floating-point number to an integer
+# 将浮点数转化成整数
>>> int(1.3)
1
```
-You can create as large an integer as you'd like; Python will allocate as much memory as needed (and ultimately, as is available) to store an integer's exact value:
+整数想多大都可以;Python会分配相应该数字所需的内存来完全存储它(而不会丢失精度)。当然,说到底这还是受有多少内存可用的限制:
```python
-# you can make an integer as large as you'd like
+# 你可以创建一个很大的整数
>>> large_int = 281938481039848500192847576920
```
-Integers have some built-in functions available to them, which are detailed in the [official documentation](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types). The utility of these will likely be quite obscure to new programmers. Just note that they are here for now.
+整数有一些内置函数可用。完整的介绍可以在[官方说明文档](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types)中找到。很多这些函数的作用可能对新手而言比较难以理解。现在你只需要知道这些函数存在就行。
-### Floating-Point Numbers
-A "floating-point" number is a number with a decimal point. Referred to as a "float" for short, this can be used to represent any number, up to a limited number of digits.
+### 浮点数
+一个浮点数(floating-point number,或float)是有小数点的数字。这可以用来表达任何数字,但其精度受数字位数的限制。
-These objects belong to the built-in type `float`, which can be used to convert objects to floats:
+这些对象属于内置类 `float`,而 `float` 则可以用来将其它对象转化成浮点数:
```python
-# examples of "floating-point" numbers
+# 几个浮点数的例子
>>> 100. ** 0.5
10.0
@@ -219,117 +218,114 @@ These objects belong to the built-in type `float`, which can be used to convert
>>> type(-2.1)
float
-# the integer 10 is not a float-type object
+# 整数 10 并不是浮点数
>>> isinstance(10, float)
False
-# including a decimal makes the number a float
+# 但加上一个小数点会让其成为浮点数
>>> isinstance(10., float)
True
-# converting a string to a floating-point number
+# 将字符串转化成浮点数
>>> float("10.456")
10.456
-# converting an integer to a floating-point number
+# 将整数转化成浮点数
>>> float(-22)
-22.0
```
-Floats have a couple of built-in functions available to them, as detailed in the [official documentation](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float).
+浮点数有几个内置的函数可用。具体内容在[官方说明文件](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float)中可以查阅。
-#### Scientific Notation
-A float can also be created using familiar scientific notation. The character `e` is used to represent $\times 10$, and the proceeding number is the exponent. Here are some examples of traditional scientific notation, and their corresponding representation in Python:
+#### 科学计数法
+浮点数也可以用常见的科学计数法来创建。字符 `e` 用来代表 $\times 10$,而在这字符后的数字是幂。以下为几个传统的科学计数法例子和它们对应的Python表达式:
$1.38 \times 10^{-4} \rightarrow$ `1.38e-04`
$-4.2 \times 10^{10} \rightarrow$ `-4.2e10`
-Python will automatically display a float that possesses many digits in scientific notation:
+Python将自动用科学计数法来显示位数多的浮点数:
```python
-# python will display many-digit numbers using
-# scientific notation
->>> 0.0000001 # seven leading-zeros
+# Python会用科学计数法来显示多位浮点数
+>>> 0.0000001 # 7个前置0
1e-07
```
-#### Understanding Numerical Precision
-Whereas a Python integer can be made to be as large as you'd like, a floating-point number is *limited in the number of digits it can store*. That is, your computer will only use a set amount of memory, 8 bytes (32 bits) on most machines, to store the value of a floating-point number.
+#### 理解数字精度
+虽然Python整数无大小限制,浮点数的精度*受限于它能存储多少位数*。具体来讲,你的电脑只会用固定量的内存(在大部分机器上是8字节,也就是32比特)来储存一个浮点数的值。
+
+实际操作时,这意味着一个浮点数大概只能存储16位有效数字的*数值精度*。计算机并不能保证存这8字节之外的位数精度。比如说,接下来的代码定义了一个100位的整数。但当这个整数被转化成浮点数后,它只能保存16位的有效数字:
-In effect, this means that a float can only be represented with a *numerical precision* of approximately 16 decimal places, when that number is written in scientific notation. The computer will not be able to reliably represent a number's digits beyond those accounted for by the allotted 8 bytes. For instance, the following Python integer is defined with 100 digits, but when this number is converted to a float, it only retains 15 decimal places in scientific notation:
```python
-# Demonstrating the finite-precision of a float.
+# 演示浮点数的有限精度
-# An integer with 100 digits - Python will use as
-# much memory as needed to store an integer
->>> int("1"*100) # creates a string with 100 1s and makes it an int
+# 一个100位的整数
+# Python会分配足够多的的内存来存储这个整数
+>>> int("1"*100) # 创建一个含有100个“1”的字符串并将其转化成整数
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
-# Converted to a float, it retains only
-# 16 decimal places, when written in scientific
-# notation. This is the precision permitted by
-# 8 bytes of memory.
->>> float("1"*100) # creates a string with 100 1s and makes it a float
+# 当将同样的字符串转化成浮点数时,
+# 它只能存储16位的有效数字
+# 这也就是8字节内存能存储的大小
+>>> float("1"*100) # 创建一个含有100个“1”的字符串并将其转化成浮点数
1.111111111111111e+99
```
-The computer cannot keep track of those last 84 decimal places because doing so would require more than 8 bytes of memory to store the entire value of that float. If you had been diligently counting stars in the sky (perhaps across many universes, this number far exceeds the estimated number of stars in our universe), you would have just lost track of over $1\times10^{83}$ of them simply by converting your integer count to a float!
+计算机无法存储最后84位数字的原因是这样做会需要远超于8字节的内存去存储整个浮点数。假如你在数星星的话,用浮点数而不是整数来存储这个数字会让你漏掉其中整整 $1\times10^{83}$ 个!
-As such, attempting to modify a floating point number in decimal places beyond its numerical precision does not have any effect:
+因此,试图用超过浮点数精度的数值去修改该浮点数并不会有任何效果:
```python
-# changing a float beyond its precision has no effect
+# 用超过浮点数精度的数值去修改该浮点数并不会有任何效果
>>> 1. + 1e-16
1.0
```
-Even in light of this discussion on float precision, you may be shocked and dismayed to see the following outcome of float arithmetic:
+就算有了以上对浮点精度的讨论做铺垫,你也很可能会惊讶于以下浮点运算的结果:
```python
-# the finite-precision of floats
-# result in non-obvious behavior
+# 这令人意外的结果源自浮点数的有限精度
>>> 0.1 + 0.1 + 0.1 - 0.3 == 0.
False
-# the effects of having finite numerical precision
+# 浮点数的有限精度的效果
>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
```
-This is not a quirk of Python; this is a [well-understood](https://docs.python.org/3/tutorial/floatingpoint.html) aspect of dealing with floating-point numbers with limited numerical precision. To accommodate this, don't check if two floats are "equal". Rather, you should check if they are "close enough in value".
-Let me emphasize this:
+这并不是什么Python的奇怪特征;这是一个已经被[完全理解](https://docs.python.org/3/tutorial/floatingpoint.html)的操作有限精度的浮点数的现象。为了应对这个问题,你不应该检查两个浮点数是否“相同”,而应该检查两个浮点数是否“够相近”。
+让我重点强调一下:
- **You should never check to see if two floats are exactly equal in value. Instead, you should only check that two floats are approximately equal to one another**.
+**你永远不应该检查两个浮点数是否完全相同。你应该检查两个浮点数是否足够相近。**
-The `math` module has a very nice function for this; `math.isclose` will check if the relative difference between two numbers is less than $1 \times 10^{-9}$. You can change this tolerance value along with the type of tolerance-checking used by the function; see its documentation [here](https://docs.python.org/3/library/math.html#math.isclose). Because in the previous example we compare values that are close to 0, we will check if their absolute difference is sufficiently small:
+`math` 模组有一个解决这个需求的函数;`math.isclose` 会检查两个数字之间的差是否小于 $1 \times 10^{-9}$。你可以修改这个函数使用的容忍值;详见此函数的[说明文档](https://docs.python.org/3/library/math.html#math.isclose)。因为在之前的例子中我们对比的数值都很接近0,我们将检查它们的差的绝对值是否够小:
```python
-# checking if two float values are "almost equal"
+# 检查两个浮点数是否“足够接近”
>>> import math
-# check:
+# 检查
# | (0.1 + 0.1 + 0.1 - 0.3) - 0 | < 1x10^{-9}
>>> math.isclose((0.1 + 0.1 + 0.1 - 0.3), 0., abs_tol=1e-9)
True
```
-If you do not heed this lesson, it is inevitable that you will end up with serious, hard-to-find bugs in your code. Lastly,
-when doing numerical work in Python (and any other programming language), you must understand that the finite numerical precision of floating-point numbers is a source of error, akin to error associated with imprecision with a measuring device, and should be accounted for in your analysis (if error analysis is warranted).
+如果你不记住这一课,你未来绝对会导致一些严重,难查的bug。在Python(以及任何其它编程语言)中做和数字有关的工作时,你一定要理解浮点数的有限精度是一个错误源,就像测量工具的不精确一样。因此在错误分析的时候要考虑到它(如果你需要做错误分析的话)。
-Python's [decimal module](https://docs.python.org/3.0/library/decimal.html) can be used to define higher (or lower) precision numbers than permitted by the standard 8-byte floats. Furthermore, all arithmetic involving decimal numbers from this module is guaranteed to be *exact*, meaning that `0.1 + 0.1 + 0.1 - 0.3` would be exactly `0.`. There is also a built-in [fractions module](https://docs.python.org/3/library/fractions.html#module-fractions), which provides tools for working with exact representations of rational numbers. Although we will not be using them here, it is very important to keep in mind that these modules exist and that floating point numbers are not the only way around the number line in Python.
+你可以用Python的[decimal模组](https://docs.python.org/3.0/library/decimal.html)来定义比标准8字节的浮点数更高(或更低)精度的数字。任何使用这个模组的数学计算都是*完全精确*的,也就是说 `0.1 + 0.1 + 0.1 - 0.3` 正好是 `0.`。Python还有一个自带的[fractions模组](https://docs.python.org/3/library/fractions.html#module-fractions)提供精确表达和操作有理数的工具。虽然我们不会在本资源中使用这些模组,但是你也应该知道这些模组的存在以及浮点数并不是唯一的选择这事实。
-### Complex Numbers
-In mathematics, a "complex number" is a number with the form $a + bi$, where $a$ and $b$ are real-valued numbers, and $i$ is defined to be the number that satisfies the relationship $i^2 = -1$. Because no real-valued number satisfies this relationship, $i$ is called the "imaginary number".
+### 复数
+在数学中,一个“复数”(complex number)是任何 $a + bi$ 形式的数字($a$ 和 $b$ 为实数,$i$ 的定义为满足 $i^2 = -1$ 关系的数)。因为没有任何实数满足上述关系,$i$ 被称为“虚数”。
-Weirdo electrical engineers use the symbol $j$ in place of $i$, which is why Python displays the complex number $2 + 3i$ as `2+3j` (this is actually because $i$ typically denotes current; we like electrical engineers too).
+奇奇怪怪的电气工程师用符号 $j$ 来代替 $i$,所以Python会将复数 $2 + 3i$ 打印成 `2+3j`(实际原因是 $i$ 一般用来表达电流;我们还是要爱护电气工程师的)。
-Along with the `a + bj` syntax, built-in type `complex` can be used to create complex-type numbers:
+除了 `a + bj` 格式之外,内置的 `complex` 类可以用来创建复数:
```python
-# creating complex numbers
+# 创建复数
>>> 2 + 3j
(2+3j)
@@ -346,22 +342,21 @@ complex
True
```
-Note that `j` is not, by itself, reserved as a special placeholder for $i$. Rather, `j` must be preceded immediately with a numerical literal (i.e. you cannot use a variable) in order for the Python interpreter to treat it as a complex number.
+请注意,`j` 自身并不是代表 $i$ 的特殊字符。只有在一个数字常量(numerical literal)(不是变量的数字)后的 `j` 才会被Python直译器理解为复数。
```python
-# `j` by itself is treated like any other character
+# 仅仅 'j' 本身并没有什么特殊含义
>>> j
-NameError: name 'j' is not defined
+NameError: name 'j' is not defined(名字 'j' 未定义)
-# `1j` is interpreted as the imaginary number
+# 而 `1j` 会被理解为虚数
>>> (1j) ** 2
(-1+0j)
```
-You can access `a` and `b` from `a + bj`, the real and imaginary parts of the complex number, respectively.
+你分别可以获取 `a + bj` 中的 `a` 和 `b`,也就是复数的实数(real)和虚数(imaginary)部分。
```python
-# Accessing the real and imaginary parts of
-# a complex number.
+# 获取复数的实数和虚数部分
>>> x = complex(1.2, -3.4)
>>> x.real
1.2
@@ -369,15 +364,15 @@ You can access `a` and `b` from `a + bj`, the real and imaginary parts of the co
-3.4
```
-The `cmath` ("complex math") module provides a collection of mathematical functions defined for complex numbers. For a complete listing of these functions, refer to the [official documentation](https://docs.python.org/3/library/cmath.html#module-cmath).
+`cmath`(“complex math”)模组定义了一组复数的数学函数。完整的列表可以在[官方说明文件](https://docs.python.org/3/library/cmath.html#module-cmath)找到。
-**Reading Comprehension: Working with numbers in Python**
+**阅读理解:操作Python数字**
-1\. In Python, performing an arithmetic operation, such as addition or multiplication, on two integers will return an integer, and performing an operation on two floats will return a float:
+1\. 在Python中,对两个整数进行如加或乘的算术会返回一个整数,而对两个浮点数进行运算会返回一个浮点数:
```python
>>> 2 * 3
6
@@ -386,37 +381,37 @@ The `cmath` ("complex math") module provides a collection of mathematical functi
6.0
```
-For which operation, among `+ - * / **`, does this *not* hold?
+上述语句对 `+ - * / **` 这些运算符中哪个*不*成立?
-2\. What type of number will be returned if you perform a mathematical operation using an integer and a floating-point number? Does this hold for all the arithmetic operations? Determine this by trial and error.
+2\. 对一个整数和一个浮点数进行数学运算会返回哪种数字?是否所有的运算符都遵循这一规律?请在命令行中进行尝试以得到答案。
-3\. Given the function $f(x) = e^{|x - 2|}$, make use of the `math` module to compute $f(-0.2)$.
+3\. 定义 $f(x) = e^{|x - 2|}$。使用 `math` 模组来运算 $f(-0.2)$。
-4\. Using Python's syntax for scientific notation, write an expression that verifies that one trillion divided by one billion is equal to one thousand
+4\. 使用Python的科学计数法语法来确认一万亿除以十亿等于一千。
-### Augmented Assignment Statements
-Python provides a nice "shortcut" for updating a variable via an arithmetic operation. For example, suppose you want to increase the value of `x` by 1. Currently, we would update `x` as follows:
+### 赋值语句的简写
+Python提供了一些方便你使用数学运算符更新变量的方式。假设你想要将 `x` 的值增加 1,你可能会如此操作:
```python
-# incrementing `x` by 1
+# 将 `x` 增加 1
>>> x = 5
>>> x = x + 1
>>> x
6
```
-We can make use of a special assignment operation `+=` to perform this update in an abbreviated way.
+我们可以利用一个特殊的赋值符 `+=` 来简写这个更新操作。
```python
-# using `+=` to increment `x` by 1
+# 使用 `+=` 来将 `x` 增加 1
>>> x = 5
->>> x += 1 # equivalent to: `x = x + 1`
+>>> x += 1 # 这和 `x = x + 1` 等值
>>> x
6
```
-`+=` is a type of *augmented assignment statement*. In general, an augmented assignment performs a mathematical operation on a variable, and then updates that variable using the result. Augmented assignment statements are available for all of the arithmetic operations. Assuming `x` and `n` are both types of numbers, the following summarizes the available arithmetic augmented assignment statements that we can perform on `x`, using `n`:
+`+=` 是一种*增强赋值语句*(augmented assignment statement)。总的来讲,一个增强赋值语句会对一个函数进行某种数学运算,并用运算的结果更新该函数。每个算术运算符都有着相对应的增强的赋值语句。假设 `x` 和 `n` 为数字,以下列表将总结我们可以用 `n` 对 `x` 进行的增强算术赋值语句:
- `x += n` $\rightarrow$ `x = x + n`
- `x -= n` $\rightarrow$ `x = x - n`
@@ -427,59 +422,59 @@ We can make use of a special assignment operation `+=` to perform this update in
-### Improving The Readability of Numbers
-Python version 3.6 introduced the ability to include underscores between the digits of a number as a visual delimiter. This character can be used to improve the readability of long numbers in your code. For example the number `662607004` can be rewritten as `662_607_004`, using `_` to delimit digits separated by orders of one thousand. Leading, trailing, or multiple underscores in a row are not allowed; otherwise this character can be included anywhere within a numerical literal.
+### 提升数字的可读性
+Python 3.6版本提供了在数字位数之间插入下划线来视觉上划分它们的功能。这个符号可以用来提升多位数的可读性。比如说,利用 `_` 来区分每三位的数字,`662607004` 可以被重写成为 `662_607_004`。下划线不能出现在数字首位,尾位,或另一个下划线旁边,但除此以外这个符号可以出现在数字常量中间的任何位置。
```python
-# examples of using `_` as a visual delimiter in numbers
->>> 1_000_000 # this is nice!
+# 利用 `_` 来视觉上划分数字
+>>> 1_000_000 # 这很实用!
1000000
-# this is gross but is permitted
+# 虽然看起来挺恶心的,但这是合法的Python代码
>>> 2_3_4.5_6_7
234.567
-# underscores work with all variety of numerical literals
+# 你可以在任何类型的数字中插入下划线
>>> 10_000j
10000j
```
-**Compatibility Warning**
+**兼容性警告**
-The permitted use of the underscore character, `_`, in numerical literals was introduced in Python 3.6. Thus utilizing this syntax in your code will render it incompatible with Python 3.5 and earlier.
+在数字常量中插入下划线 `_` 的功能是在Python 3.6版本加入的。如果你使用此功能,那你的代码会和Python 3.5和更早的版本不兼容。
-## The Boolean Type
-There are two boolean-type objects: `True` and `False`; they belong to the built-in type `bool`. We have already seen that the `isinstance` function either returns `True` or `False`, as a given object either is or isn't an instance of a specific type.
+## 布尔类
+Python有两种布尔类(boolean)的对象:`True`(真)和 `False`(否);它们属于内置的 `bool` 类型。我们在之前见到 `isinstance` 函数根据对象是否是某类的实例(instance)而返回 `True` 或 `False`。
```python
-# the two boolean-objects: `True` and `False`
+# 两种布尔类的对象:`True` 和 `False`
>>> type(True)
bool
-# `False` is a boolean-type object
+# `False` 是一个布尔类的对象
>>> isinstance(False, bool)
True
```
-`True` and `False` must be specified with capital letters in Python. These should not be confused with strings; note that there are no quotation marks used here.
+在Python中,`True` 和 `False` 必须要首字母大写。请不要将它们和字符串搞混;注意布尔值并两边没有引号。
-### Logic Operators
-Python provides familiar operators for performing basic boolean logic:
+### 逻辑运算符
+Python提供常见的布尔逻辑的操作符:
-| Logic Operation | Symbolic Operator
-| --------------- | ------------------- |
-| `and` | `&` |
-| `or` | | |
+| 逻辑运算名称 | 运算符号 |
+| ------------ | -------- |
+| `and`(逻辑与) | `&` |
+| `or` (逻辑或) | | |
```python
-# demonstrating boolean-logic operators
+# 演示布尔逻辑运算符
>>> True or False
True
@@ -490,24 +485,26 @@ False
True
```
-Operator symbols are available in place of the reserved words `and` and `or`:
+译者注:原文因为 `not`(逻辑否)在英文中很好理解没有多讨论。读者只需知道:`not` 返回输入的布尔值的反值。
+
+你也可以使用 `and` 和 `or` 对应的运算符号:
```python
-# demonstrating the symbolic logic operators
->>> False | True # equivalent to: `False or True`
+# 演示逻辑运算符
+>>> False | True # 和 `False or True` 等值
True
->>> False & True # equivalent to: `False and True`
+>>> False & True # 和 `False and True` 等值
False
```
-That being said, it is generally more "Pythonic" (i.e. in-vogue with Python users) to favor the use of the word-operators over the symbolic ones.
+一般来讲,使用运算名称,而不是符号,是更加“Python风格“的做法(也就是说这个方法在Python编程者之间更时兴)。
-Multiple logic operators can be used in a single line and parentheses can be used to group expressions:
+你可以在同行使用多个逻辑运算符,并用括号来细述运算顺序:
```python
>>> (True or False) and True
True
```
-Comparison statements used in basic mathematics naturally return boolean objects.
+基本的比大小语句自然会返回布尔类的对象。
```python
>>> 2 < 3
True
@@ -519,12 +516,12 @@ False
False
```
-The `bool` type has additional utilities, which will be discussed in the "Conditional Statements" section.
+`bool` 类有着其它方便操作的方法。我们将在“条件语”小节讨论它们。
-### Boolean Objects are Integers
-The two boolean objects `True` and `False` formally belong to the `int` type in addition to `bool`, and are associated with the values `1` and `0`, respectively:
+### 布尔值对象其实就是整数
+`True` 和 `False` 这两个布尔值对象正式而言也是 `int` 类型的成员,其分别对应 `1` 和 `0`:
```python
>>> isinstance(True, int)
@@ -540,47 +537,48 @@ True
0
```
-As such, they can be used in mathematical expressions interchangeably with `1` and `0`
+因此,在数学运算中它们和 `1` 和 `0` 的作用一样:
```python
->>> 3*True - False # equivalent to: 3*1 + 0
+>>> 3*True - False # 和 3*1 + 0 等值
3
->>> True / False # equivalent to: 1 / 0
+>>> True / False # 和 1 / 0 等值
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
in ()
----> 1 True / False
ZeroDivisionError: division by zero
+(因为除以零所以直译器报错)
```
-The purpose of having `True` and `False` double as integers is beyond the scope of this section. It is simply useful to be aware of these facts so that this behavior is not completely alien to you as you begin to write code in Python.
+为何 `True` 和 `False` 同时也是整数的原因超出了本节的纲领。熟悉这一特征会让你在写Python代码的时候避免一些错误。
-**Reading Comprehension: Boolean expressions**
+**阅读理解:布尔表达式**
-1\. Assuming `x` is a an integer-type, write a comparison statement that will return `True` if `x` is an even number, and `False` otherwise. (Hint: recall the purpose of the `%` operator)
+1\. 假设 `x` 是整数类。编写一个表达式,在 `x` 是偶数时返回 `True`,其它情况返回 `False`。(提示:回忆 `%` 运算符的功能)
-2\. Assuming `x` and `y` are both real-valued numbers (i.e. not complex numbers), write a line of code that will return `False` if: `x` and `y` are within 0.9 of one another, and `x` is a positive number. (Hint: try writing the expression that will return `True` for this condition, and then negate it)
+2\. 假设 `x` 和 `y` 都是实数(也就是不是复数的数字)。编写一行代码,在以下情况中返回 `False`:`x` 和 `y` 相差小于0.9,且 `x` 大于零。(提示:尝试先编写在这个情况中会返回 `True` 的代码,然后再取反)
-3\. Write an expression that returns `True` if `x` is a boolean-type object or a float-type object.
+3\. 编写一个表达式,当 `x` 是布尔类型或浮点类型对象时返回 `True`。
-## The None-Type
-There is a simple type, `NoneType` that has exactly one object: `None`. `None` is used to represent "null"... nothing.
+## None类型
+`NoneType`(None类型)仅仅只有一个对象:`None`。`None` 用来表达“无”/“空”,也就是什么都没有的意思。
```python
-# `None` is the *only* object belonging to NoneType
+# `None` 是*唯一*属于NoneType的对象
>>> type(None)
NoneType
```
-As such, instead of checking if an object belongs to NoneType, you should simply check if the object is `None`. Python reserves `is` as an operation that checks if two objects are identical. This is different than `==`, which checks if two objects are associated with the same value or state:
+因此,与其检查某对象是否属于NoneType,你应该直接检查该对象是否就是 `None`。Python保留 `is` 为检查两个对象是否相同的运算符。这和检查两个对象是否有着同样的值或态的 `==` 运算符不一样:
```python
-# Check if an object "is" None, instead
-# of checking if it is of NoneType
+# 检查对象是否*是*(is)None,而不是
+# 检查对象是否是NoneType类的实例
>>> x = 22
>>> x is None
@@ -594,14 +592,15 @@ True
>>> y is None
True
```
-`None` appears frequently, and is often used as a placeholder in code. Here is a simple example where `None` could be useful; don't worry that this code may not make perfect sense to you yet:
+译者注:`x is not None` 和 `not (x is None)` 等值,但前者因更符合英文语法而也被支持。
+
+`None` 经常作为占位符使用。以下代码将演示 `None` 在实际操作中的用法;如果你并不能完全理解这代码,不要担心:
```python
-# Demonstrating the use of `None` as a placeholder
+# 演示将 `None` 作为占位符的用法
-# In this code, we want to get the first
-# item in a list that is greater than 10, and notify
-# the user if there is no such number
+# 在本代码中,我们想要找到列表中第一个大于10的物件
+# 如果该物件不存在,我们将如实告诉用户
large_num = None
@@ -617,42 +616,41 @@ if large_num is None:
-## Strings
-### Introducing the string type
-The string type is used to store written characters. A string can be formed using:
+## 字符串
+### 字符串类型简介
+字符串(string)类型被用于存储多个字符。你可以用一下语法创建字符串:
-- single quotes: `'Hello world'`
-- double quotes: `"Hello world"`
-- triple quotes: `"""Hello world"""` or `'''Hello world'''`
+- 单引号:`'Hello world'`
+- 双引号:`"Hello world"`
+- 三引号:`"""Hello world"""` 或 `'''Hello world'''`
```python
-# Strings contain written characters, even those
-# not found in the english alphabet!
+# 字符串可以存储任何字符,
+# 不仅仅是英文字母表中的字母!
>>> "hello, 你好, Olá, 123"
'hello, 你好, Olá, 123'
```
-By default, Python 3 uses [UTF-8 unicode](https://docs.python.org/3/howto/unicode.html#unicode-howto) to represent this wide variety of characters. Don't worry about this detail beyond making note of it, for now.
+Python 3默认使用[UTF-8 unicode](https://docs.python.org/3/howto/unicode.html#unicode-howto)来表达这些多样化的字符。暂时没必要太过关注这个细节,知道它存在就行。
-Strings belong to the built-in `str` type, which can be used to convert non-string objects into strings.
+字符串属于内置的 `str` 类型。`str` 则可以用来将非字符串对象转化成字符串。
```python
-# the type `str`
+# `str` 类型
>>> type("hello")
str
>>> isinstance("83", str)
True
-# Using the type `str` to convert non-string objects
-# into strings.
+# 利用 `str` 类型来将非字符串对象转化成字符串
>>> str(10.34)
'10.34'
>>> str(True)
'True'
```
-Once a string is formed, it cannot be changed (without creating an entirely new string). Thus a given string object cannot be "mutated" - a string is an *immutable* object.
+当一个字符串被创建后,它的值无法被改变(除非你创建一个全新的字符串)。因此,任何一个字符串都无法被“改变”——字符串是*不可变*(immutable)的对象。
-As the string stores a *sequence* of characters, Python provides a means for accessing individual characters and subsequences of characters from a string:
+因为Python存储一*序列*(sequence)的字符,Python提供了调用字符串中单个字符和子字符串的工具:
```python
>>> sentence = "The cat in the hat."
>>> sentence[0]
@@ -660,24 +658,24 @@ As the string stores a *sequence* of characters, Python provides a means for acc
>>> sentence[0:3]
'The'
```
-Strings are not the only sequence-type in Python; lists and tuples are examples of sequences as well. We will reserve a separate section to learn about the common interface that Python has for all of its types that are sequential in nature, including the "indexing" and "slicing" demonstrated here.
+字符串并不是Python中唯一的序列类;列表(list)和元组(tuple)也同样是序列的一种。我们在未来将专门花一节课来讨论Python提供的通用序列操作。这包括了以上展示的“索引“(indexing)和”切片“(slicing)。
-### String essentials
-We will only scratch the surface with strings, touching on some essentials. Please refer to the [official Python tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) for a more extensive, but still informal, overview of strings.
+### 字符串基础
+我们只会学习一些字符串的基础。如果你想要一个更全面的非正式字符串教程,请查阅[官方Python教程](https://docs.python.org/3/tutorial/introduction.html#strings)。
-In a string, `\n` is treated as a single character. It denotes a new-line in a string, and will be rendered thusly when the string is printed. Similarly, `\t` will render as a tab-character.
+在字符串中,`\n` 被视为一个字符。它代表着字符串的新行(new-line)。在打印时它也会如此显示。相似的 `\t` 会显示为一个tab字符。
```python
-# using `\n` to create a newline
+# 使用 `\n` 来创建新行
>>> print("hi...\n...bye")
hi...
...bye
```
-Using triple quotes allows you to write a block-string, meaning that you can include text on multiple lines, and it is all still treated as one string:
+三引号将允许你编写一整块字符串,也就是说你可以在多行中编写同一个字符串:
```python
-# using triple-quotes to write a multi-line string
+# 使用三引号来编写一个多行字符串
>>> x = """ I am a string.
I am part of the same string.
me... too!"""
@@ -687,80 +685,146 @@ I am part of the same string.
```
-Python's strings have a large number of fantastic, built-in functions available to them. It is *very important* that you familiarize yourself with these functions by looking over [the official documentation](https://docs.python.org/3/library/stdtypes.html#string-methods). To demonstrate a few of these:
+Python的字符串有着大量很有用的内置函数。熟悉了解这些函数*极其重要*。详见[官方说明文件](https://docs.python.org/3/library/stdtypes.html#string-methods)。以下是其中一些函数的演示:
```python
-# demonstrating a few of the built-in functions for strings
->>> "hello".capitalize()
+# 演示几个字符串的内置函数
+>>> "hello".capitalize() # 译者注:首字母大写
'Hello'
-# join a list of strings, using "..."
+# 使用“...”来讲多个字符串连接在一起
>>> "...".join(["item1", "item2", "item3"])
'item1...item2...item3'
-# split a string wherever ", " occurs
+# 每当“, ”出现时切分字符串
>>> 'item1, item2, item3'.split(", ")
['item1', 'item2', 'item3']
-# does this string end with ".py"?
+# 该字符串是否以“.py”结尾?
>>> "script.py".endswith(".py")
True
-# does this string start with "sc"?
+# 该字符串是否以“sc”打头?
>>> "script.py".startswith("sc")
True
-# insert objects into a string, in its
-# "formatting" fields {}
+# 在占位符 {} 中将对象转化为字符串并插入
>>> "x: {}, y: {}, z: {}".format(3.2, 8.4, -1.0)
'x: 3.2, y: 8.4, z: -1.0'
-# Are the characters in the string
-# numerical digits?
+# 该字符串的字符是否时数字位数?
>>> "7".isdigit()
True
```
-### Official documentation for strings
-It is highly recommended that you take time to read over all of the functions that are built-in to a string.
+### 格式化字符串
+Python提供多种设置字符串格式的语法;利用这些语法,我们可以轻松地将变量数值插入到字符串中,利用空格对齐行列,并控制字符串显示小数点后几位数。本节旨在向读者展示这些不同的字符串格式。
+
+如果你想要完整(但仍然易懂)的Python字符串格式教程,请查阅[pyformat.info](https://pyformat.info)。你也可以查阅[官方教程](https://docs.python.org/3/library/string.html#format-examples)。
+
+在Python 3中,你可以使用 `format` 方法来格式化字符串:
+
+```python
+# 使用 `format` 来用函数值代替占位符
+>>> "{name} is {age} years old".format(name="Bruce", age=80)
+'Bruce is 80 years old'
+
+# 以下语法会前置空格来保证字符串至少有8字符长
+>>> "{item:>8}".format(item="stew")
+' stew'
+```
+你有时可能会见到别人用 `%` 运算符来格式化字符串:
+
+```python
+# 使用 `%` 来格式化字符串(注意不要使用此方法)
+>>> name = "Selina"
+>>> "My name is %s" % name
+'My name is Selina'
+```
+这是Python 2的遗留物;你应注意避免使用此语法。
+
+如果你在用Python 3.6和之后的版本,你可以使用f-string(f字符串),一种很方便格式化字符串的方法。以下是一个f字符串的范例:
+
+```python
+# “f字符串”范例
+>>> batman = 12
+>>> catwoman = 10
+>>> f"Batman has {batman} apples. Catwoman has {catwoman} apples. Together, they have {batman + catwoman} apples"
+'Batman has 12 apples. Catwoman has 10 apples. Together, they have 22 apples'
+```
+
+请注意f字符串是一种特殊语法;在第一个引号前输入小写字符f来使用f字符串:
+```python
+# 这是一个常见的空字符串
+>>> ""
+''
+
+# 这是一个空的f字符串
+>>> f""
+''
+```
+
+f字符串的特殊之处在于它允许我们在字符串*中*编写Python代码;任何在 `{}` 中的表达式都会作为Python代码被执行,其结果将会被转化成字符串并插入在 `{}` 在f字符串中的位置。
-- [Built-in functions for strings](https://docs.python.org/3/library/stdtypes.html#string-methods)
-- [Formatting strings](https://docs.python.org/3.4/library/string.html#format-examples)
+```python
+>>> x = 7.9
+>>> f"x is a {type(x)}-number. Its value is {x}. The statement 'x is greater than 5' is {x > 5}"
+"x is a -number. Its value is 7.9. The statement 'x is greater than 5' is True"
+(“x是一个浮点数类数字。它的值为7.9。表达式‘x大于5’为真”)
+```
+
+如例中所见,这将允许我们优雅地在字符串创建时插入变量并甚至调用函数的输出。
+
+
-**Reading Comprehension: Strings**
+**阅读理解:字符串**
-To answer some of the following questions, you will need to peruse the documentation for the built-in functions of strings. It may take a bit of experimentation to understand the documentation's use of square-brackets to indicate optional inputs for a function.
+为了回答以下问题,你会需要查阅字符串内置函数的说明文档。你可能需要进行一些尝试才能理解说明文档的“[]”格式(用于表达函数的可选输入)。
-1\. Use a function that will take the string `"cat"`, and returns the string `" cat "` (which has a length of 11, including the letters c, a, t). Now, change the way you call the function so that it returns `"----cat----"` instead.
+1\. 使用一个函数,在输入字符串 `"cat"` 时返回字符串 `" cat "`(输出的长度为11个字符;这包含字符c,a,t)。之后,修改你调用该函数的方法以返回 `"----cat----"`。
-2\. Replace the first three periods of this string with a space-character: `"I.am.aware.that.spaces.are.a.thing"`
+2\. 用空格代替以下字符串的前三个句号:`"I.am.aware.that.spaces.are.a.thing"`
-3\. Remove the whitespace from both ends of: `" basket "`
+3\. 去除该字符串两边的所有空格:`" basket "`。
-
-4\. Create a string that will print as (the second line begins with a tab-character):
+
+4\. 创建一个打印时会如下显示的字符串(第二行打头的是一个tab符号):
```
Hello
over there
```
-5\. Convert the integer `12` to the string `"12"`.
+5\. 将整数 `12` 转化成字符串 `"12"`。
+
+6\. 只有13岁和以上的孩子可以观看电影《反斗智多星》。设变量 `name`(字符串)和 `age`(整数)。使用f字符串来显示:"NAME is old enough to watch the movie: BOOL"(“NAME可以看这电影:BOOL”)。NAME应该用孩子的名字来代替,而BOOL在孩子13岁或以上时为 `True`,不然为 `False`。
-
-## Lists
-A `list` is a type of Python object that allows us to store a sequence of other objects. One of its major utilities is that it provides us with means for updating the contents of a list later on.
+## 列表
+一个 `list`(列表)是一个允许我们存储一序列Python对象的对象。列表的一大功能就是我们在未来可以更新列表中的内容。
-A list object is created using square-brackets, and its contents are separated by commas: `[item1, item2, ..., itemN]`. Its contents need not be of the same type of object.
+你可以用方括号来创建列表,并用逗号区分其中的成员:`[item1, item2, ..., itemN]`。它的成员可以是各种不同的类型。
+
+译者注:注意使用英文的方括号和逗号。
```python
-# a list-type object stores a sequence of other objects
+# 列表对象可以存储一序列的其它对象
>>> [3.5, None, 3.5, True, "hello"]
[3.5, None, 3.5, True, 'hello']
@@ -768,142 +832,141 @@ A list object is created using square-brackets, and its contents are separated b
list
>>> isinstance([1, 2], list)
-True
+True
-# constructing an empty list
+# 空列表
>>> []
[]
-# constructing a list with only one member
+# 只有一个成员的列表
>>> ["hello"]
["hello"]
```
-You can also include variables, equations, and other Python expressions in the list constructor; Python will simplify these expressions and construct the list with the resulting objects.
+你也可以在创建列表时使用变量,公式,和其它Python表达式;Python会计算这些表达式并用计算的结果作为列表的成员。
```python
-# the list constructor will simplify expressions
-# and store their resulting objects
+# 创建列表时会计算表达式并储存计算后的输出对象
>>> x = "hello"
>>> [2 < 3, x.capitalize(), 5**2, [1, 2]]
[True, 'Hello', 25, [1, 2]]
```
-The built-in `list` type can be used to convert other types of sequences (and more generally, any *iterable* object, which we will discuss later) into a list:
+内置的 `list` 类型可以用来将其它任何类型的序列(更广义来讲,任何*可迭代*的对象——我们会在之后对其进行讨论)转化成列表:
```python
-# `list` forms a list out of the contents of other sequences
+# `list` 利用其它序列的内容来创建新列表
>>> list("apple")
['a', 'p', 'p', 'l', 'e']
```
-### Lists are sequences
-Like a string, the ordering of a list's contents matters, meaning that a list is sequential in nature.
+### 列表是序列
+就像字符串一样,列表内容的排列顺序是很重要的。这也就是说,列表是序列性(sequential)的。
```python
-# A list's ordering matters
+# 列表是分顺序的
>>> [1, "a", True] == [1, True, "a"]
False
```
-Thus a list supports the same mechanism for accessing its contents, via indexing and slicing, as does a string. Indexing and slicing will be covered in detail in the next section.
+因此,像字符串一样,你可以通过索引(indexing)和切片(slicing)来访问列表的内容。我们将在下一节中更具体地介绍索引和切片。
```python
-# Accessing the contents of a list with indexing and slicing
+# 通过索引和切片来访问列表的内容
>>> x = [2, 4, 6, 8, 10]
-# `x` contains five items
+# `x` 里有5个物件
>>> len(x)
5
-# access the 0th item in the list via "indexing"
+# 通过索引来访问列表的第0个物件
>>> x[0]
2
-# access a subsequence of the list via "slicing"
+# 通过切片来访问列表的子序列
>>> x[1:3]
[4, 6]
```
-### Lists can be "mutated"
-We will encounter other types of containers in Python, what makes the list stand out is that the *contents of a list can be changed after the list has already been constructed*. Thus a list is an example of a *mutable* object.
+### 列表是可变的
+我们会在之后遇到其它的Python容器。使得列表不同的是*列表的内容可以在列表创建后被修改*。因此,列表是*可变*对象的一种。
```python
-# changing a list after it has been constructed
+# 在列表被创建后修改它
>>> x = [2, 4, 6, 8, 10]
>>> y = [2, 4, 6, 8, 10]
-# "set" the string 'apple' into position 1 of `x`
+# 将列表 `x` 第1位的物件“设置”(set)成字符串 'apple'
>>> x[1] = "apple"
>>> x
[2, 'apple', 6, 8, 10]
-# replace a subsequence of `y`
+# 修改 `y` 的子序列
>>> y[1:4] = [-3, -4, -5]
>>> y
[2, -3, -4, -5, 10]
```
-The built-in list-functions "append" and "extend" allow us to add one item and multiple items to the end of a list, respectively:
+自带的列表函数“append”和“extend”允许我们分别在列表结尾添加一个和多个的成员:
```python
>>> x = [2, 4, 6, 8, 10]
-# use `append` to add a single object to the end of a list
+# 用 `append` 在列表结尾添加一个对象
>>> x.append("moo")
>>> x
[2, 4, 6, 8, 10, 'moo']
-# use `extend` to add a sequence of items to the end of a list
+# 用 `extend` 在列表结尾添加一序列的对象
>>> x.extend([True, False, None])
>>> x
[2, 4, 6, 8, 10, 'moo', True, False, None]
```
-The "pop" and "remove" functions allow us to remove an item from a list based on its position in the list, or by specifying the item itself, respectively.
+“pop”和“remove”函数允许我们分别根据成员在列表中的位置和值来将它们从列表中移出。
```python
>>> x = ["a", "b", "c", "d"]
-# pop the position-1 item out from a list
-# `pop` will return the item that gets removed.
+# 将列表中位置1的物件“pop”(跳)出来
+# `pop` 会返回被移出的物件
>>> x.pop(1)
'b'
>>> x
['a', 'c', 'd']
-# remove the object "d" from the list
+# 将对象 `"d"` 从列表中移出
>>> x.remove("d")
>>> x
['a', 'c']
```
-### Official documentation for lists
-It is highly recommended that you take time to read over all of the functions that are built-in to a list. These are all designed to allow us to either inspect or mutate the contents of a list.
+### 列表的官方说明文档
+本文强烈建议读者花些时间了解列表的所有自带函数。这些函数都旨在帮助我们访问或修改列表的内容。
-- [Built-in functions for a list](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
+- [列表的内置函数](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
-**Reading Comprehension: Lists**
+**阅读理解:列表**
-To answer some of the following questions, you will need to peruse the documentation for the built-in functions of lists.
+为了回答以下问题,你会需要查阅列表内置函数的说明文档。
-1\. Create a list whose sole entry is the `None` object.
+1\. 创建一个列表,其唯一的物件是 `None` 对象。
-2\. Assign to the variable `k` a list that contains an integer, a boolean, and a string, in that order. Then, add two more entries to the end of the list: a float and a complex number.
+2\. 向变量 `k` 赋值一个内容为一个整数,一个布尔值,和一个字符串(顺序也是如此)的列表。然后在列表结尾添加两个项目:一个浮点数和一个复数。
-3\. Alphabetize the list of names: `["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"]`.
+3\. 根据字母顺序排序以下列表:`["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"]`。
-## Summary
-The term "object" is a catch-all in Python, meaning anything that we can assign to a variable. Objects behave differently from one another according to what "type" a given object is.
+## 总结
+“对象”(object)在Python中泛指任何可以赋值于一个变量的东西。对象根据其“类型”(type)不同会有不同的行为。
-We reviewed several fundamental object types in Python:
+我们复习了Python几种不同的基本对象类型:
-- `int`, `float`, `complex`: the numerical types
-- `bool`: the boolean type. `True` and `False` are the only boolean-type objects
-- `NoneType`: the "null" type; `None` is *the only object that belongs to this type*
-- `str`: the string type
-- `list`: the list type
+- `int`,`float`,`complex`:数字类型
+- `bool`:布尔(boolean)类型,其唯二的布尔类对象为 `True` 和 `False`
+- `NoneType`:“空”类;`None` 是*唯一的这类对象*
+- `str`:字符串类
+- `list`:列表类
-The built-in function `type` permits us to check the type of any object:
+Python自带的 `type` 函数允许我们查看任何对象的类型:
```python
>>> type(3.2)
float
@@ -912,20 +975,20 @@ float
bool
```
-The built-in function `isinstance` should be used to check if an object is of a specific type:
+我们应该用自带的 `isinstance` 函数来查看一个对象是否属于某类型:
```python
>>> x = 2 + 3
>>> isinstance(x, int)
True
```
-The only exception to this is if you want to check if an object is of the type `NoneType`, since this is only possible if the object is `None`; thus it is "cleaner" to directly check this:
+唯一例外的是当你想要检查某个对象是否属于 `NoneType` 类型,因为这类型只有 `None` 一个对象;因此,如下直接检查会更加“干净”:
```python
>>> x = None
>>> x is None
True
```
-Objects of different types have different built-in functions available to them:
+不同类型的对象有着不同的内置函数可用:
```python
>>> x = "I am a farmer.. moo"
>>> x.upper()
@@ -941,17 +1004,17 @@ Objects of different types have different built-in functions available to them:
[1, 2, 3]
```
-You should leverage the official documentation, for which links were provided throughout this section, whenever you are wondering how to best do a specific task with a given type of object.
+当你在试图寻找操作某类型对象的最佳方法时,你应当查阅官方说明文档(本节多次提供其链接)。
-As a final reminder, we saw that that an integer in Python is able to hold a value with arbitrarily-many digits. A floating-point number, on the other hand, is restricted in the number of "significant" digits it can hold. Thus, where it is perfectly fine to check if two integers are exactly equal:
+最后,Python整数类可以存储任意多的位数,而浮点数只能存储有限的“有效”位数。因此,你可以直接检查两个整数是否完全相等:
```python
-# checking if two integers are equal is great!
+# 检查两个整数是否完全相等没有任何问题!
>>> 2 + 2 == 4
True
```
-you should never rely on two floats being exactly equal. Instead, check if they are close in value:
+但你不应该检测两个浮点数是否完全相等。你应该检查它们的值是否足够接近:
```python
-# checking if two floats are equal is lame!
+# 检查两个浮点数是否完全相等会有一些奇怪的结果!
>>> 0.1 + 0.1 + 0.1 - 0.3 == 0.
False
@@ -959,37 +1022,37 @@ False
True
```
-It is very important to remember this issue of the limited numerical precision of a floating point number.
+切记浮点数的有限精度问题。
-## Links to Official Documentation
+## 官方说明文档链接
-- [Integers](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types)
-- [Floating point numbers](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float)
-- [The standard library's math module](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions)
-- [The standard library's complex-valued math module](https://docs.python.org/3/library/cmath.html#module-cmath)
-- [Strings](https://docs.python.org/3/library/stdtypes.html#string-methods)
- - [String tutorial](https://docs.python.org/3/tutorial/introduction.html#strings)
- - [Formatting strings](https://docs.python.org/3.4/library/string.html#format-examples)
-- [Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
+- [整数](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types)
+- [浮点数](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float)
+- [标准库的math模组](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions)
+- [标准库的复数math模组](https://docs.python.org/3/library/cmath.html#module-cmath)
+- [字符串](https://docs.python.org/3/library/stdtypes.html#string-methods)
+ - [字符串教程](https://docs.python.org/3/tutorial/introduction.html#strings)
+ - [字符串格式](https://docs.python.org/3.4/library/string.html#format-examples)
+- [列表](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
-## Reading Comprehension Exercise Solutions:
+## 阅读理解答案
-**Understanding the modulo operator: Solution**
+**理解模运算符:解**
-If `n` is an integer, then 2 will divide into it evenly, and thus there is no remainder. If `n` is odd, then `n / 2` must have a remainder of 1. Thus:
+如果 `n` 是偶数,那么它将被2整除,所以余数为0。如果 `n` 是单数,那 `n / 2` 的余数为1。所以:
-- `n % 2 ` = 0 if `n` is an even number
-- `n % 2 ` = 1 if `n` is an odd number
+- 当 `n` 是偶数时 `n % 2 ` = 0
+- 当 `n` 是单数时 `n % 2 ` = 1
-**Working with numbers in Python: Solution**
+**操作Python数字:解**
-1\. The division operator, `/`, will return a floating-point number even if it is operating on two integer-type numbers.
+1\. 除法操作符 `/` 永远都会返回浮点数,就算它在将两个整数相除。
-2\. For all of the arithmetic operations, `+ - * / **`, operating on a floating-point number and an integer will return a floating-point number:
+2\. 所有算术运算符 `+ - * / **` 对一个整数一个浮点数操作时都会返回一个浮点数:
```python
>>> 2 * 3.0
6.0
@@ -998,7 +1061,7 @@ If `n` is an integer, then 2 will divide into it evenly, and thus there is no re
1.0
```
-3\. Given the function $f(x) = e^{|x - 2|}$, make use of the `math` module to compute $f(-0.2)$.
+3\. 设函数 $f(x) = e^{|x - 2|}$。用 `math` 模组来计算 $f(-0.2)$。
```python
>>> from math import exp
>>> x = -0.2
@@ -1006,9 +1069,9 @@ If `n` is an integer, then 2 will divide into it evenly, and thus there is no re
9.025013499434122
```
-4\. Using Python's syntax for scientific notation, write an expression that verifies that one trillion divided by one billion is equal to one thousand.
+4\. 使用Python的科学计数法语法来确认一万亿处以十亿等于一千。
-> As cautioned above, we should avoid checking to see if two floating point numbers are exactly equal, and instead simply ensure that they are close in value. Keep in mind that a number written Python's using scientific syntax will produce a float.
+> 如上文所警示的一样,我们应该避免检查两个浮点数是否完全相等,而应当检查两浮点数是否足够相近。注意在Python中用科学计数法写出的数字会是浮点类的。
```python
>>> from math import isclose
@@ -1018,34 +1081,34 @@ True
-**Boolean expressions: Solutions**
+**布尔表达式:解**
```python
-# 1. Write an a comparison-statement that will return
-# True if x is an even number
+# 1. 编写一个表达式,在 `x` 是偶数时返回 `True`,
+# 其它情况返回 `False`。
x%2 == 0
```
```python
-# 2. Write a line of code that will return False if:
-# x and y are within 0.9 of one another, and x is a positive number.
+# 2. 编写一行代码,在以下情况中返回 `False`:
+# `x` 和 `y` 相差小于0.9,且 `x` 大于零。
not (abs(x - y) < 0.9 and 0 < x)
-# alternatively,
+# 或者
abs(x - y) > 0.9 or 0 > x
```
```python
-# 3. Write an expression that returns True if
-# x is a boolean-type object or a float-type object
+# 3. 编写一个表达式,当 `x` 是布尔类型
+# 或浮点类型对象时返回 `True`。
isinstance(x, bool) or isinstance(x, float)
```
-**Strings: Solutions**
+**字符串:解**
```python
-# 1. Use a function that will take the string "cat"
-# and returns the string " cat "
+# 1. 使用一个函数,在输入字符串 `"cat"` 时
+# 返回字符串 `" cat "`
>>> "cat".center(11)
' cat '
@@ -1054,15 +1117,13 @@ isinstance(x, bool) or isinstance(x, float)
```
```python
-# 2. Replace the first three periods of this string with
-# a space-character:
+# 2. 用空格代替以下字符串的前三个句号:
>>> "I.am.aware.that.spaces.are.a.thing".replace(".", " ", 3)
'I am aware that.spaces.are.a.thing'
```
```python
-# 3. Remove the whitespace from both ends
-# of: " basket "
+# 3. 去除该字符串两边的所有空格:`" basket "`
>>> " basket ".strip()
'basket'
```
@@ -1075,26 +1136,41 @@ Hello
```
```python
-# 5. Convert the integer 12 to the string "12"
+# 5. 将整数 `12` 转化成字符串 `"12"`。
>>> str(12)
'12'
```
+
+只有13岁和以上的孩子可以观看电影《反斗智多星》。假设你有函数 `name`(字符串)和 `age`(整数)。使用f字符串来显示:"NAME is old enough to watch the movie: BOOL"(“NAME可以看这电影:BOOL”)。NAME应该用孩子的名字来代替,而BOOL在孩子至少13岁以上时应为 `True`,不然为 `False`。为测试我们使用 `name = "Alfred"`,`age = 10`.
+
+```python
+# 6. 只有13岁和以上的孩子可以观看电影《反斗智多星》。
+# 假设你有函数 `name`(字符串)和 `age`(整数)。
+# 使用f字符串来显示:"NAME is old enough to watch
+# the movie: BOOL"(“NAME可以看这电影:BOOL”)。
+# 用NAME应该用孩子的名字来代替,而BOOL在孩子至少13岁以上
+# 时应为 `True`,不然是 `False`。
+>>> name = "Alfred"
+>>> age = 10
+>>> f"{name} is old enough to watch the movie: {age >= 13}"
+'Alfred is old enough to watch the movie: False'
+```
+
-**Lists: Solutions**
+**列表:解**
```python
-# Create a list whose sole entry is the None object.
+# 创建一个列表,其唯一的物件是 `None` 对象。
>>> [None]
[None]
```
```python
-# 2. Assign the variable k to a list that contains an
-# integer, a boolean, and a string, in that order.
-# Then, add two more entries to the end of the
-# list - a float and a complex number.
+# 2. 向变量 `k` 赋值一个内容为一个整数,一个布尔值,
+# 和一个字符串(顺序也是如此)的列表。然后在列表结尾
+# 添加两个项目:一个浮点数和一个复数。
>>> k = [4, False, "moo"]
>>> k.extend([3.14, complex(9, -2)])
>>> k
@@ -1102,13 +1178,13 @@ Hello
```
```python
-# 3. Alphabetize the list of names:
+# 3. 根据字母顺序排序以下列表:
>>> names = ["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"]
-# The documentation for `sort` says that the sorting happens "in-place". This
-# means that the original list is replaced by the sorted list. The alternative
-# would be that `sort` returns a new, sorted list, without changing the list
-# assigned to `names`.
+# `sort` 的说明文档说排序是“in-place”(当场)的,
+# 这意思就是原本的列表会被新的排序好的列表代替。
+# 如果不是“in-place”的话,那可能 `sort` 会返回一个排序好
+# 的列表,而不修改原本名为 `names` 的列表。
>>> names.sort()
>>> names
['Adam', 'Bob', 'Jack', 'Jackenzie', 'Jane', 'Ryan', 'Zordon']
diff --git a/Python/Module2_EssentialsOfPython/ConditionalStatements.md b/Python/Module2_EssentialsOfPython/ConditionalStatements.md
index 95af737..c2d86e4 100644
--- a/Python/Module2_EssentialsOfPython/ConditionalStatements.md
+++ b/Python/Module2_EssentialsOfPython/ConditionalStatements.md
@@ -4,108 +4,108 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Conditional Statements, Difficulty: Easy, Category: Section
:keywords: if, else, elif, inline if, switch statement, comparison operator, bool, truth, is operator
-```
+
-# Conditional Statements
+# 条件语
-**Note**:
+**注**:
-There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.
+在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-In this section, we will be introduced to the `if`, `else`, and `elif` statements. These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false. For example, the following code will square `x` if it is a negative number, and will cube `x` if it is a positive number:
+在本节中,我们将会介绍 `if`,`else`,和 `elif` 语句。它们允许你编写仅仅在某些条件满足时才会执行的代码片段,或者在条件不满足时执行某些其它代码。比如说,以下代码在 `x` 是负数的时候返回 `x` 的平方,在 `x` 是正数时返回 `x` 的立方:
```python
-# a simple if-else block
+# 简单的if-else区块
if x < 0:
x = x ** 2
else:
x = x ** 3
```
-Please refer to the "Basic Python Object Types" subsection to recall the basics of the "boolean" type, which represents True and False values. We will extend that discussion by introducing comparison operations and membership-checking, and then expanding on the utility of the built-in `bool` type.
+请通过“基本对象类型“一节来回忆布尔类型(代表真或否值)的一些基础特征。我们将会延续该节的讨论来介绍比较运算和成员检查,并讨论内置 `bool` 类的更多有用之处。
-## Comparison Operations
-Comparison statements will evaluate explicitly to either of the boolean-objects: `True` or `False`. There are eight comparison operations in Python:
+## 比较运算
+比较语句(comparison statement)最后一定会返回某个布尔对象:`True` 或 `False`。在Python中总共有八种比较运算:
-| Operation | Meaning |
+| 运算符 | 含义 |
| --------- | ----------------------- |
-| `<` | strictly less than |
-| `<=` | less than or equal |
-| `>` | strictly greater than |
-| `>=` | greater than or equal |
-| `==` | equal |
-| `!=` | not equal |
-| `is` | object identity |
-| `is not` | negated object identity |
+| `<` | 小于(不等于) |
+| `<=` | 小于或等于 |
+| `>` | 大于(不等于) |
+| `>=` | 大于或等于 |
+| `==` | 等于 |
+| `!=` | 不等于 |
+| `is` | 相同对象 |
+| `is not` | 不相同对象 |
-The first six of these operators are familiar from mathematics:
+其中前六个运算符和数学中常见的相对应:
```python
>>> 2 < 3
True
```
-Note that `=` and `==` have very different meanings. The former is the assignment operator, and the latter is the equality operator:
+注意 `=` 和 `==` 有着两个很不一样的含义。前者是赋值运算符,而后者是等值运算符:
```python
->>> x = 3 # assign the value 3 to the variable `x`
->>> x == 3 # check if `x` and 3 have the same value
+>>> x = 3 # 对变量 `x` 赋值 3
+>>> x == 3 # 检查 `x` 和 3 是否有着同样的值
True
```
-Python allows you to chain comparison operators to create "compound" comparisons:
+Python允许你连接多个对比运算符来创建“复式”(compound)对比:
```python
->>> 2 < 3 < 1 # performs (2 < 3) and (3 < 1)
+>>> 2 < 3 < 1 # 等值于 (2 < 3) and (3 < 1)
False
```
-Whereas `==` checks to see if two objects have the same value, the `is` operator checks to see if two objects are actually the *same* object. For example, creating two lists with the same contents produces two *distinct* lists, that have the same "value":
+`==` 运算符检查两个对象是否有着同样的值,而 `is` 运算符检查两个对象是否是*相同的*对象。比如说,创建两个有着一样内容的列表会得到两个*不同*的列表,但它们的“值”一样:
```python
-# demonstrating `==` vs `is`
+# 演示 `==` 对比 `is`
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
-# `x` and `y` reference equivalent, but distinct lists
+# `x` 和 `y` 引用两个等值但不同的列表
>>> x is y
False
```
-Thus the `is` operator is most commonly used to check if a variable references the `None` object, or either of the boolean objects:
+因此 `is` 运算符最常用来检查一个变量是否引用 `None` 对象,或两个布尔对象中的一个:
```python
>>> x = None
>>> x is None
True
-# (2 < 0) returns the object `False`
-# thus this becomes: `False is False`
+# (2 < 0) 返回对象 `False`
+# 因此这会成为:`False is False`
>>> (2 < 0) is False
True
```
-Use `is not` to check if two objects are distinct:
+使用 `is not` 来检查两个对象是否不是同一个对象:
```python
>>> 1 is not None
True
@@ -113,8 +113,8 @@ True
-## `bool` and Truth Values of Non-Boolean Objects
-Recall that the two boolean objects `True` and `False` formally belong to the `int` type in addition to `bool`, and are associated with the values `1` and `0`, respectively:
+## `bool` 和非布尔类对象的真值
+请回忆两个布尔对象 `True` 和 `False` 严格来讲即属于 `bool` 也属于 `int` 类型,并分别有着值 `1` 和 `0` 这些知识点:
```python
>>> isinstance(True, int)
@@ -141,43 +141,43 @@ ZeroDivisionError Traceback (most recent call last)
ZeroDivisionError: division by zero
```
-Likewise Python ascribes boolean values to non-boolean objects. For example,the number 0 is associated with `False` and non-zero numbers are associated with `True`. The boolean values of built-in objects can be evaluated with the built-in Python command `bool`:
+类似的,Python也会对非布尔对象提供相应的布尔值。比如说,数字0对应着 `False`,而任何非0的数字则对应 `True`。内置对象的布尔值可以通过Python内置的命令 `bool` 来得出:
```python
-# Using `bool` to access the True/False
-# value of non-boolean objects
+# 使用 `bool` 来查看非布尔类对象
+# 的布尔值为 `True` 或 `False`
>>> bool(0)
False
```
-and non-zero Python integers are associated with `True`:
+任何非0的Python整数对应 `True`:
```python
-# nonzero values evaluate to `True`
+# 非0值最后计算为 `True`
>>> bool(2)
True
```
-The following built-in Python objects evaluate to `False` via `bool`:
+以下的内置Python对象通过 `bool` 对应 `False`:
- `False`
- `None`
-- Zero of any numeric type: `0`, `0.0`, `0j`
-- Any empty sequence, such as an empty string or list: `''`, `tuple()`, `[]`, `numpy.array([])`
-- Empty dictionaries and sets
+- 任何数字类的0:`0`, `0.0`, `0j`
+- 任何空序列,如空字符串或列表:`''`,`tuple()`,`[]`,`numpy.array([])`
+- 空词典(dictionary)或集(set)
-Thus non-zero numbers and non-empty sequences/collections evaluate to `True` via `bool`.
+因此任何非0的数字或非空的序列或集合都会通过 `bool` 对应 `True`。
-**Takeaway**:
+**经验**:
-The `bool` function allows you to evaluate the boolean values ascribed to various non-boolean objects. For instance, `bool([])` returns `False` wherease `bool([1, 2])` returns `True`.
+`bool` 函数允许你得到非布尔类对象对应的布尔值。比如说,`bool([])` 返回 `False`,而 `bool([1, 2])` 返回 `True`。
-## `if`, `else`, and `elif`
-We now introduce the simple, but powerful `if`, `else`, and `elif` conditional statements. This will allow us to create simple branches in our code. For instance, suppose you are writing code for a video game, and you want to update a character's status based on her/his number of health-points (an integer). The following code is representative of this:
+## `if`,`else`,和 `elif`
+我们现在将介绍简单而强大的 `if`,`else`,和 `elif` 条件语句(conditional statement)。这将允许我们在代码中创建简单的分枝。比如说,假设你在为某电子游戏编写代码,并想要根据你角色的血量(整数)来更新ta的状态,下面的代码就是一个例子:
```python
if num_health > 80:
@@ -190,102 +190,99 @@ else:
status = "dead"
```
-Each `if`, `elif`, and `else` statement must end in a colon character, and the body of each of these statements is [delimited by whitespace](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope).
+每个 `if`,`elif`,和 `else` 语句必须由冒号结尾,且其中所有语句都必须由[空格限定](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python使用空格来限定区域)。
-The following pseudo-code demonstrates the general template for conditional statements:
+以下的伪代码演示条件语句的通用模版:
```
if :
- the code within this indented block is executed if..
- - bool() is True
+ 本缩进区域的代码只有在以下条件满足时才会被执行...
+ - bool() 为 True
elif :
- the code within this indented block is executed if..
- - bool() was False
- - bool() is True
+ 本缩进区域的代码只有在以下条件满足时才会被执行...
+ - bool() 之前为 False
+ - bool() 为 True
...
...
elif :
- the code within this indented block is executed if..
- - bool() was False
- - bool() was False
+ 本缩进区域的代码只有在以下条件满足时才会被执行...
+ - bool() 之前为 False
+ - bool() 之前为 False
...
...
- - bool() was False
- - bool() is True
+ - bool() 之前为 False
+ - bool() 为 True
else:
- the code within this indented block is executed only if
- all preceding expressions were False
+ 本缩进区域的代码只有在
+ 之前所有表达式为 False 时
+ 才会被执行...
```
-In practice this can look like:
+实际运用时它可以看起来是这样:
```python
x = [1, 2]
if 3 < len(x):
- # bool(3 < 2) returns False, this code
- # block is skipped
+ # bool(3 < 2) 返回 False,所以此区块的代码将被跳过
print("`x` has more than three items in it")
elif len(x) == 2
- # bool(len(x) == 2) returns True
- # this code block is executed
+ # bool(len(x) == 2) 返回 True,此区块的代码被执行
print("`x` has two items in it")
elif len(x) == 1
- # this statement is never reached
+ # 此语句根本没有被检查
print("`x` has one items in it")
else:
- # this statement is never reached
+ # 此语句根本没有被检查
print("`x` is an empty list")
"`x` has two items in it"
```
-In its simplest form, a conditional statement requires only an `if` clause. `else` and `elif` clauses can only follow an `if` clause.
+在最简洁的格式下,一个条件语句只需要一个 `if` 句段。`else` 和 `elif` 句段只能在一个 `if` 句段之后。
```python
-# A conditional statement consisting of
-# an "if"-clause, only.
-
+# 一个只有“if”句段的条件语句
x = -1
if x < 0:
x = x ** 2
-# x is now 1
+# `x` 现在为 1
```
-Similarly, conditional statements can have an `if` and an `else` without an `elif`:
+类似的,条件语句可以有一个 `if` 和一个 `else` 而没有任何 `elif`:
```python
-# A conditional statement consisting of
-# an "if"-clause and an "else"
+# 一个有一个“if”句段和一个“else”句段
+# 的条件语句
x = 4
if x > 2:
x = -2
else:
x = x + 1
-# x is now -2
+# `x` 现在为 -2
```
-Conditional statements can also have an `if` and an `elif` without an `else`:
+条件语句也可以有一个 `if` 和一个 `elif` 而没有 `else`:
```python
-# A conditional statement consisting of
-# an "if"-clause and an "elif"
+# 一个有一个“if”句段和一个“elif”句段
+# 的条件语句
x = 'abc'
if len(x) < 9:
x = x * 3
elif len(x) > 40:
x = 'cba'
-# x is now 'abcabcabc'
+# `x` 现在为 'abcabcabc'
```
-Note that only one code block within a single if-elif-else statement can be executed: either the "if-block" is executed, or an "elif-block" is executed, or the "else-block" is executed. Consecutive if-statements, however, are completely independent of one another, and thus their code blocks can be executed in sequence, if their respective conditional statements resolve to `True`.
+请注意在一个if-elif-else语句中只有其中一段可以被执行;要么“if”区块的代码被执行,要么一个“elif”区块的代码被执行,要么“else”区块的代码被执行。但是,背靠背的if语句是完全独立于对方的。因此它们的代码区块可能在单次运行中都被执行(假设它们对应的条件语句都最后为 `True`)。
```python
-# consecutive if-statements are independent
+# 连续的if语句是互相独立的
x = 5
y = 0
@@ -295,16 +292,16 @@ if x < 10:
if x < 20:
y += 1
-# y is now 2
+# y 现在为 2
```
-**Reading Comprehension: Conditional statements**
+**阅读理解:条件语句**
-1\. Assume `my_list` is a list. Given the following code:
+1\. 设 `my_list` 为一个列表。根据以下代码:
```python
first_item = None
@@ -312,13 +309,13 @@ if my_list:
first_item = my_list[0]
```
-What will happen if `my_list` is `[]`? Will `IndexError` be raised? What will `first_item` be?
+如果 `my_list` 为 `[]`,会发生什么?这是否会产生一个 `IndexError`?`first_item` 会是什么?
-2\. Assume variable `my_file` is a string storing a filename, where a period denotes the end of the filename and the beginning of the file-type. Write code that extracts only the filename.
+2\. 设变量 `my_file` 为一个存储着文件名的字符串,其中英文句号 `.` 代表着文件名的结尾和文件类型的开始。编写代码来获取 `my_file` 的文件名。
-`my_file` will have at most one period in it. Accommodate cases where `my_file` does *not* include a file-type.
+`my_file` 中最多只会有一个句号。妥善处理 `my_file` *没有*文件类型的情况。
-That is:
+也就是说:
- `"code.py"` $\rightarrow$ `"code"`
- `"doc2.pdf"` $\rightarrow$ `"doc2"`
@@ -328,8 +325,8 @@ That is:
-### Inline if-else statements
-Python supports a syntax for writing a restricted version of if-else statements in a single line. The following code:
+### 单行的if-else语句
+Python支持一个单行版本的if-else语句,其功能比较有限。以下代码:
```python
if num >= 0:
@@ -338,31 +335,31 @@ else:
sign = "negative"
```
-can be written in a single line as:
+可以被简写成:
```python
sign = "positive" if num >=0 else "negative"
```
-This is suggestive of the general underlying syntax for inline if-else statements:
+这代表了单行(inline)if-else语句的内在语法:
-**The inline if-else statement**:
+**单行if-else语句**:
-The expression `A if else B` returns `A` if `bool()` evaluates to `True`, otherwise this expression will return `B`.
+表达式 `A if else B` 当 `bool()` 为 `True` 时返回 `A`,不然该表达式会返回 `B`。
-This syntax is highly restricted compared to the full "if-elif-else" expressions - no "elif" statement is permitted by this inline syntax, nor are muli-line code blocks within the if/else clauses.
+和完整的“if-elif-else”表达式对比,这个语法是极其受限制的——它不允许“elif”语句,也不允许if/else之间有多行的代码块。
-Inline if-else statements can be used anywhere, not just on the right side of an assignment statement, and can be quite convenient:
+单行if-else语句可以在任何地方使用,不仅仅是在赋值语句的右侧。这有时很方便:
```python
-# using inline if-else statements in different scenarios
+# 在不同情况下使用单行if-else语句
>>> x = 2
-# will store 1 if `x` is non-negative
-# will store 0 if `x` is negative
+# 如 `x` 并不是负数,这将储存 1
+# 如 `x` 为负数,这将储存 0
>>> my_list = [1 if x >= 0 else 0]
>>> my_list
[1]
@@ -370,31 +367,31 @@ Inline if-else statements can be used anywhere, not just on the right side of an
>>> "a" if x == 1 else "b"
'b'
```
-We will see this syntax shine when we learn about comprehension statements. That being said, this syntax should be used judiciously. For example, inline if-else statements ought not be used in arithmetic expressions, for therein lies madness:
+我们将在讨论列表理解语句(list comprehension statement)时注意到这个语法很有用的地方,但请注意谨慎使用这一语法。比如说,不要在数学表达式中使用单行if-else语句,因为最后的代码令人抓狂:
```python
-# don't ever do this...ever!
+# 永远不要这么做,永远!
2 - 3 if x < 1 else 1 + 6*2 if x >= 0 else 9
```
-## Short-Circuiting Logical Expressions
-Armed with our newfound understanding of conditional statements, we briefly return to our discussion of Python's logic expressions to discuss "short-circuiting". In Python, a logical expression is evaluated from left to right and will return its boolean value as soon as it is unambiguously determined, *leaving any remaining portions of the expression unevaluated*. That is, the expression may be *short-circuited*.
+## 短路逻辑表达式
+在对条件语句有了更深刻的理解之后,我们将扩展我们对Python逻辑表达式的研究来讨论短路(short-circuiting)。在Python中,一个逻辑表达式会从左到右运算,并在表达式结果确定的那一步就返回,且*不会运算表达式剩下的部分*。也就是说,表达式可以*短路*。
-For example, consider the fact that an `and` operation will only return `True` if both of its arguments evaluate to `True`. Thus the expression `False and ` is guaranteed to return `False`; furthermore, when executed, this expression will return `False` *without having evaluated* `bool()`.
+比如说,`and` 运算仅仅会在它两边的表达式都为 `True` 时才会返回 `True`。因此,表达式 `False and ` 一定会返回 `False`;同时,这个表达式会返回 `False` 而*不运算* `bool()`。
-To demonstrate this behavior, consider the following example:
+为了演示这一行为,请见下面的例子:
```python
-# demonstrating short-circuited logic expressions
->>> False and 1/0 # evaluating `1/0` would raise an error
+# 演示短路逻辑表达式
+>>> False and 1/0 # 运算 `1/0` 会导致错误
False
```
-According to our discussion, the pattern `False and` short-circuits this expression without it ever evaluating `bool(1/0)`. Reversing the ordering of the arguments makes this clear.
+根据上文的讨论,`False and` 会短路这个表达式,让它不运算 `bool(1/0)` 就返回。换转参数顺序会明显地揭示这一点。
```python
-# expressions are evaluated from left to right
+# 表达式是从左到右运算的
>>> 1/0 and False
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
@@ -404,66 +401,66 @@ ZeroDivisionError Traceback (most recent call last)
ZeroDivisionError: division by zero
```
-In practice, short-circuiting can be leveraged in order to condense one's code. Suppose a section of our code is processing a variable `x`, which may be either a [number](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Number-Types) or a [string](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Strings). Suppose further that we want to process `x` in a special way if it is an all-uppercased string. The code
+在实际操作中,你可以通过短路来浓缩你的代码。假设我们代码的一节在处理变量 `x`,其可能是一个[数字](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#数字类型)或[字符串](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#字符串)。假设我们当 `x` 是全大写的字符串时想要有特殊的处理方式。以下代码
```python
-# this will raise an error if `x` is not a string
+# 这在 `x` 不是字符串时会报错
if x.isupper():
- # do something with the uppercased string
+ # 对此大写字符串进行操作
```
-is problematic because `isupper` can only be called once we are sure that `x` is a string; this code will raise an error if `x` is a number. We could instead write
+是有问题的,因为 `isupper` 只应该在我们确定 `x` 是字符串之后才调用;如果 `x` 是一个数字,我们的代码会报错。我们可以重写代码
```python
-# a valid but messy way to filter out non-string objects
+# 一个可用但难看的过滤非字符串对象的方法
if isinstance(x, str):
if x.isupper():
- # do something with the uppercased string
+ # 对此大写字符串进行操作
```
-but the more elegant and concise way of handling the nestled checking is to leverage our ability to short-circuit logic expressions.
+但一个更加优雅和简短的处理多层次检测的方法是短路逻辑表达式。
```python
-# utilizing short-circuiting to concisely perform all necessary checks
+# 利用短路来简写必要的检查
if isinstance(x, str) and x.isupper():
- # do something with the uppercased string
+ # 对此大写字符串进行操作
```
-See, that if `x` is not a string, that `isinstance(x, str)` will return `False`; thus `isinstance(x, str) and x.isupper()` will short-circuit and return `False` without ever evaluating `bool(x.isupper())`. This is the preferable way to handle this sort of checking. This code is more concise and readable than the equivalent nested if-statements.
+请注意如果 `x` 不是字符串,那 `isinstance(x, str)` 会返回 `False`;因此 `isinstance(x, str) and x.isupper()` 会短路并直接返回 `False`,且不运算 `bool(x.isupper())`。这是这种检查任务的推荐结局方法。这代码对比等值的多层if语句更简短和可读。
-**Reading Comprehension: short-circuited expressions**
+**阅读理解:短路表达式**
-Consider the preceding example of short-circuiting, where we want to catch the case where `x` is an uppercased string. What is the "bug" in the following code? Why does this fail to utilize short-circuiting correctly?
+回忆前文检查 `x` 是大写字符串的范例。以下代码的“bug“是什么?为什么它并没有正确地利用短路?
```python
-# what is wrong with me?
+# 我做错了什么?
if x.isupper() and isinstance(x, str):
- # do something with the uppercased string
+ # 对此大写字符串进行操作
```
-## Links to Official Documentation
+## 官方说明文档连接
-- [bool](https://docs.python.org/3/library/functions.html#bool)
-- [Truth testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
-- [Boolean operations](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
-- [Comparisons](https://docs.python.org/3/library/stdtypes.html#comparisons)
-- ['if' statements](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)
+- [布尔值](https://docs.python.org/3/library/functions.html#bool)
+- [检查真值](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
+- [布尔操作符](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
+- [对比](https://docs.python.org/3/library/stdtypes.html#comparisons)
+- ['if'语句](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)
-## Reading Comprehension Exercise Solutions:
+## 阅读理解答案
-**Conditional statements**
+**条件语句:解**
-1\. If `my_list` is `[]`, then `bool(my_list)` will return `False`, and the code block will be skipped. Thus `first_item` will be `None`.
+1\. 如果 `my_list` 为 `[]`,那 `bool(my_list)` 会返回 `False`,而对应的代码块则会被跳过。因此 `first_item` 会是 `None`。
-2\. First, check to see if `.` is even contained in `my_file`. If it is, find its index-position, and slice the string up to that index. Otherwise, `my_file` is already the file name.
+2\. 首先,检查 `my_file` 是否包含 `.`。如果是,找到它的索引并对字符串进行切片(切到该索引)。如果不是,`my_file` 就已经是文件名了。
```python
my_file = "code.pdf"
@@ -477,14 +474,14 @@ else:
-**Short-circuited expressions**
+**短路表达式:解**
-The code
+此代码
```python
-# what is wrong with me?
+# 我做错了什么?
if x.isupper() and isinstance(x, str):
- # do something with the uppercased string
+ # 对此大写字符串进行操作
```
-fails to account for the fact that expressions are always evaluated from left to right. That is, `bool(x.isupper())` will always be evaluated first in this instance and will raise an error if `x` is not a string. Thus the following `isinstance(x, str)` statement is useless.
+并没有考虑表达式从左到右运算的顺序。也就是说,在这个例子中 `bool(x.isupper())` 永远都会首先被运算,并且会在 `x` 不是字符串时报错。因此,之后的 `isinstance(x, str)` 语句完全没用。
diff --git a/Python/Module2_EssentialsOfPython/DataStructures.md b/Python/Module2_EssentialsOfPython/DataStructures.md
index f7889e7..a313128 100644
--- a/Python/Module2_EssentialsOfPython/DataStructures.md
+++ b/Python/Module2_EssentialsOfPython/DataStructures.md
@@ -4,146 +4,145 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Data Structures, Difficulty: Medium, Category: Section
:keywords: Big-O, complexity, efficiency, algorithm, interview preparation, list, tuple, sequence
-```
+
-# Data Structures (Part I): Introduction
-Here we survey Python's built-in data structures. You should already be familiar with its lists and tuples, two data structures that facilitate working with sequential data. Two other critical, built-in data structures to be introduced are:
+# 数据结构(第一部分):简介
+我们在此介绍Python内置的数据结构(data structure)。你应该已经了解了列表和元组,两个帮助处理序列数据的数据结构。我们将会介绍另外两个重要的内置数据结构:
-- dictionary: a mapping from "keys" to "values"
-- sets: an unordered collection of items that can be used to perform set-algebraic operations (e.g. union and intersection)
+- 词典(dictionary):一对一对应“键”(key)和“值”(value)
+- 集(set):用来进行集运算(如并集和交集)的无序集合
-These data structures are not merely convenient constructs with some nice pre-written functionality; they also provide an interface to some optimized core utilities that have been written in C (or whatever language your Python interpreter is written in). For example, let's write a function that checks if an item is contained within an iterable:
+这些数据结构不仅仅是一些有着好用核心功能的方便构造题;它们同时也提供了用C语言(或你使用的Python直译器编译用的语言)编译的高效核心功能的接口。比如说,让我们来编写一个检查某对象是否为可迭代物成员的函数:
```python
def is_in(seq, target):
- """ Returns True if `target` is contained in `seq`."""
+ """ 如果 `target` 在 `seq` 中则返回真"""
for item in seq:
if item == target:
return True
return False
```
-This function mirrors the C-algorithm that Python uses "under the hood" for checking for membership in a list (assuming you are using the CPython interpreter, which you almost definitely are). Because their function is implemented "at a lower level", and need not be interpreted, we expect it to be faster than ours:
+以上函数和Python在“幕后”使用的C语言成员检测算法(当然,这是假设你在使用CPython直译器,但极大可能是这个情况)是一样的。因为内置的成员检测函数是在“更底层”实现的并因此不需要被直译,所以它比我们在Python中定义的函数更快:
```python
>>> x = [1, "moo", 3, True, 5, None, 7, 8]
->>> is_in(x, -1) # takes 980 nanoseconds on my machine
+>>> is_in(x, -1) # 在我的机子上花了 980 纳秒
False
->>> -1 in x # takes 320 nanoseconds on my machine
+>>> -1 in x # 在我的机子上花了 320 纳秒
False
```
-Here, Python's built-in sequence-membership function is 3x faster than using our own function. Furthermore, it will be important to know the advantages provided by each of the data structures. For instance, testing for membership in a set is even faster than is checking for membership in a list:
+在此,Python的内置成员检测函数比我们的版本快了三倍。同时,我们应该了解各个数据结构的优势。比如说,集(set)的成员检测比列表还要快:
```python
-# test for membership in a list
->>> -1 in [1, "moo", 3, True, 5, None, 7, 8] # takes 295 nanoseconds on my machine
+# 在列表中检测是否为成员
+>>> -1 in [1, "moo", 3, True, 5, None, 7, 8] # 在我的机子上花了 295 纳秒
False
-# test for membership in a set
->>> -1 in {1, "moo", 3, True, 5, None, 7, 8} # takes 65 nanoseconds on my machine
+# 在集中检测是否为成员
+>>> -1 in {1, "moo", 3, True, 5, None, 7, 8} # 在我的机子上花了 65 纳秒
False
```
-We get a 4.5x speedup in our membership test just by using a set instead of a list, because the use of a set permits Python to use an entirely different algorithm for checking for membership. On our end, we merely replaced square brackets with curly braces! Hopefully this is sufficient motivation for learning about Python's data structures and the algorithms that they utilize "under the hood".
+通过使用集而不是列表,我们得到了4.5倍的速度优化。这是因为集允许Python使用一个完全不同的成员检测算法。在Python程序员的角度上,我们仅仅将方括号替换成了花括号!我希望以上范例为你提供了足够学习Python数据结构和它们“幕后”使用的算法的理由。
-**Takeaway**:
+**经验**:
-Python's data structures come with a wealth of built-in functionality. Furthermore, understanding where each data structure "shines" is critical for writing efficient Python code. It is not necessary to memorize this information, but you should know that it exists and should be referenced frequently.
+Python的数据结构有着自己内置的功能。同时,理解每个数据结构适合的工作对编写高效的Python代码极其重要。你不需要死记这些信息,但是你应该知道这些信息存在并经常查阅这些信息。
-## Describing Algorithm Complexity
-In order to meaningfully compare the relative efficiency of algorithms, it is useful to summarize how algorithms "scale" with problem size. Two sorting algorithms may be comparable when sorting tens of items, and yet they may have wildly different performances when sorting thousands of items.
+## 描述算法复杂度
+为了有意义地比较算法的效率,总结算法在问题大小变化时如何表现是很有用的信息。两个排序算法可能在排列几十个项目时速度相当,但它们完全可能在排列几千个项目时有着很不一样的效率。
-"Big-O" notation allows us to denote how an algorithm's run time scales against problem size. Specifically, it signifies the "worst-case scenario" performance of an algorithm.
+“大O”符号(big-O notation)允许我们表达算法在问题大小变化时运算时间如何改变。具体来讲,它代表着算法在“最坏情况下”的表现。
-Let's take, for instance, the `is_in` function that we wrote at the beginning of this section. In it, we iterate over a collection to check if it contains a specific item. The worst-case scenario for this algorithm is when the item is not a member of the collection at all - we have to iterate over the entire collection before we can conclude that it does not possess our item. So if we increase the collection to be $n$ times larger in size, it should take $n$ times as long to iterate over it to determine that the item is not a member of the collection (again, dealing with the worst-case scenario). Because the worst-case scenario run time of `is_in` scales linearly with the size of the collection, $n$, we denote it's run time complexity, using big-O notation, as $\mathcal{O}(n)$.
+比如说,拿在本节开始写的 `is_in` 函数来讲,我们迭代了一个集合并检查它是否有着某个项目。这个算法的最坏情况就是当项目并不是集合的成员——我们需要迭代整个集合才能确定它并不拥有我们要找的项目。所以如果我们将该集合的大小扩大 $n$ 倍,那它会花 $n$ 倍多的时间来迭代整个集合并决定一个项目不是其成员(在此同样假设最坏情况)。因为 `is_in` 的最坏情况的运行时间和集合的大小 $n$ 呈线性关系,所以我们用大O符号来将该算法的运行时间复杂度写为 $\mathcal{O}(n)$。
-Now suppose we did a truly terrible job writing a membership algorithm, and performed a nested iteration over our collection:
+现在,假设我们写的成员检查函数很糟糕,其进行了嵌套迭代:
```python
def is_in_slow(seq, target):
- """ Returns True if `target` is contained in `seq`."""
+ """ 如果 `target` 为 `seq` 成员,返回真。"""
for item in seq:
- # for each item in seq, iterate over seq in its entirety!
+ # 我们为seq中的项目重新迭代整个seq!
for item2 in seq:
if item == target:
return True
return False
```
-For each item in `seq` we iterate over `seq` again, thus in the worst-case scenario we need to iterate over $n$ items, $n$ separate times - a total of $n^{2}$ "steps" in our algorithm. Thus we would say that `is_in_slow` is a $\mathcal{O}(n^{2})$ algorithm: whereas doubling size of `seq` would increase the run time of our $\mathcal{O}(n)$ algorithm by a factor of 2 (linear scaling), it would increase the run time of this $\mathcal{O}(n^{2})$ algorithm by 4 (quadratic scaling).
+我们为 `seq` 中的每个项目重新迭代 `seq` 一次,因此在最坏情况下我们需要迭代 $n$ 个成员 $n$ 次——总共在算法中走了 $n^{2}$ “步”。因此,我们说 `is_in_slow` 是一个 $\mathcal{O}(n^{2})$ 的算法:当我们将 `seq` 的大小翻倍时,我们的 $\mathcal{O}(n)$ 算法会花两倍多的时间(线性增加),而我们的 $\mathcal{O}(n^{2})$ 算法会花四倍多的时间(平方增加)。
-Here is a more formal description of this notation:
+以下是大O符号更加正式的定义:
-**"Big-O" Notation**: Suppose that $n$ denotes the "size" of the input to an algorithm, and that the mathematical expression $f(n)$ describes how many computational steps the algorithm must take in its *worst-case scenario*, given that input. Then the algorithm's run time complexity can be denoted using the **"Big-O"** notation: $\mathcal{O}(f(n))$.
+**“大O”符号**(big-O notation):假设 $n$ 代表着算法输入的“大小”,且数学表达式 $f(n)$ 描述该算法在*最坏情况*下需要花多少计算步骤处理大小为 $n$ 的输入,那么算法的运行时间复杂度用**“大O”符号**表达为 $\mathcal{O}(f(n))$。
-A few important notes:
+几个重要的点:
-- We only care about the "highest-order" term in $f(n)$. That is, $\mathcal{O}(n + n^{2})$ should just be written as $\mathcal{O}(n^{2})$.
-- We never care about constant factors in our scaling. That is, even if an algorithm iterates over a sequence twice, its big-O complexity should be written as $\mathcal{O}(n)$, rather than $\mathcal{O}(2n)$.
-- An algorithm whose run time *does not depend on the size of its input* is a $\mathcal{O}(1)$ algorithm.
- - Example: a function that returns the second element from a list.
-- There are more nuanced methods for analyzing algorithm complexity than solely considering the worst-case scenario, which can be overly pessimistic. Know that "big-O" notation can be used to convey mean performance, [amortized](https://en.wikipedia.org/wiki/Amortized_analysis) performance, and other types of analysis. Here, we will simply stick to the worst-case analysis.
+- 我们仅仅在乎 $f(n)$ 最高次数的项。也就是说,$\mathcal{O}(n + n^{2})$ 应被写为 $\mathcal{O}(n^{2})$。
+- 我们永远不在乎关系中的常数。也就是说,就算一个算法迭代某序列两次,它的大O复杂度应该被写为 $\mathcal{O}(n)$,而不是 $\mathcal{O}(2n)$。
+- 一个运行时间*不根据输入大小而改变*的算法是一个 $\mathcal{O}(1)$ 算法。
+ - 例:一个返回列表中第二个成员的函数。
+- 我们有其它更加微妙,不仅仅考虑最坏情况的分析算法复杂度的方法,因为最坏情况分析可能太过悲观。“大O”符号“也可以用来代表平均表现,[摊销](https://en.wikipedia.org/wiki/Amortized_analysis)(amortized)表现,和其它分析类型。在此,我们仅仅使用最坏情况分析。
-**Takeaway**:
+**经验**:
-We will be using the "big-O" notation, $\mathcal{O}(f(n))$, to summarize the performance of the algorithms used by Python's data structures.
+我们将会使用“大O”符号 $\mathcal{O}(f(n))$ 来总结Python数据结构使用的算法的表现。
-## Sequential Data Structures: Lists and Tuples
-The "Sequence Types" section already introduced lists and tuples. Recall that both provide the same interface for accessing and summarizing the contents of a heterogeneous sequence of objects. However, a list can be mutated - updated, removed from, and added to - whereas a tuple cannot be mutated. Thus a list is *mutable*, whereas a tuple is *immutable*. Here you will find a summary of the algorithmic complexities of many of the built-in functions that work on sequential data structures.
+## 序列性数据结构:列表和元组
+“序列类型”小节已经介绍了列表和元组。请回忆这两个数据结构都提供了相同的交互界面来访问和总结其不同类型对象的成员序列。但是,列表是可以被改变的——你可以对其更新,删除,并添加项目——而元组不可变。因此列表*可变*,而元组*不可变*。在本节你将会找到很多操作序列数据结构的内置函数的算法复杂度。
-For a complete rundown of the functions available to Python's list, go [here](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists).
+你可以在[这里](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)找到所有的Python列表函数。
-#### List/Tuple Complexities
-Let `seq` represent a **list or tuple** of length $n$; $i$ and $j$ are integers drawn randomly from the interval $[0, n-1]$; $k$ is the length of any subsequence involved in the operation. The following is a summary of the complexities associated with various common operations using lists and tuple (according to their implementations in CPython):
+#### 列表/元组复杂度
+设 `seq` 为长度为 $n$ 的**列表或元组**;$i$ 和 $j$ 为从区间 $[0, n-1]$ 中随意抽取的整数;$k$ 为任何在此操作中使用的子序列的长度。以下为各种常见的列表和元组操作(根据CPython的实现)的复杂度:
-|Operation| Complexity | Explanation |
+|操作| 复杂度 | 解释 |
|---|---|---|
-|`len(seq)`|O(1)| Return the number of items in the sequence |
-|`seq[i]`| O(1) | Retrieve any item from the sequence |
-|`seq[i:j]`| O(k) | Retrieve a length-k slice from the sequence |
-|`for item in seq..`| O(n) | Iterate over the sequence |
-|`obj in seq`| O(n) | Check if `obj` is a member of `seq` |
-|`seq.count(obj)`| O(n) | Count the number of occurrences of `obj` in `seq` |
-|`seq.index(obj)`| O(n)| Return position-index of `obj` in `seq` |
+|`len(seq)`| O(1)| 返回序列中成员的数量 |
+|`seq[i]`| O(1) | 从序列中获取单个成员 |
+|`seq[i:j]`| O(k) | 从序列中获取长度k的切片 |
+|`for item in seq..`| O(n) | 迭代序列 |
+|`obj in seq`| O(n) | 检查 `obj` 是否为 `seq` 的成员 |
+|`seq.count(obj)`| O(n) | 返回 `obj` 在 `seq` 出现的次数 |
+|`seq.index(obj)`| O(n)| 返回 `obj` 在 `seq` 中的索引 |
-#### List Complexities
-Here we consider some mutating operations, like `append`, that are available to lists and not tuples. It is important to note that lists are implemented such that:
+#### 列表复杂度
+我们在此考虑一些列表可用而元组不可用的改变序列的操作,如 `append`。请注意列表的实现导致:
-- operations that add-to or remove-from the *end* of the list are $\mathcal{O}(1)$
-- operations that add-to or remove-from the *beginning* of the list are $\mathcal{O}(n)$
+- 在列表*结尾*添加或删除成员的操作为 $\mathcal{O}(1)$
+- 在列表*开头*添加或删除成员的操作为 $\mathcal{O}(n)$
-Let `my_list` represent a list of length $n$, and `i` is an integer drawn randomly from the interval $[0, n-1]$. The following is a summary of the complexities associated with various operations using a list (according to its implementation in CPython):
+设 `my_list` 为长度为 $n$ 的列表,而 `i` 为从区间 $[0, n-1]$ 随意抽取的整数。以下为列表各种操作(在CPython实现中)的复杂度:
-|Operation| Complexity | Explanation |
+|操作| 复杂度 | 解释 |
|---|---|---|
-|`my_list[i] = obj`| O(1) | Set the ith entry of the list with a new object. |
-|`my_list.append(obj)`| O(1) | Append a new object to the end of the list. |
-|`my_list.pop()`| O(1) | Remove the object from the *end* of the list. |
-|`my_list.pop(0)`| O(n) | Remove the object from the *beginning* of the list. |
-|`my_list.sort()`| O(nlog(n)) | Return a sorted version of the list. |
-
+|`my_list[i] = obj`| O(1) | 将列表第i位的项目设为新对象。|
+|`my_list.append(obj)`| O(1) | 在列表结尾添加新对象。|
+|`my_list.pop()`| O(1) | 删除在列表*结尾*的对象。|
+|`my_list.pop(0)`| O(n) | 删除在列表*开头*的对象。|
+|`my_list.sort()`| O(nlog(n)) | 返回同列表的顺序版本。|
diff --git a/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md b/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md
index 5cc59ad..3c66f8f 100644
--- a/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md
+++ b/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md
@@ -4,67 +4,67 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Introduction to Sets, Difficulty: Medium, Category: Section
:keywords: set, complexity, comparison, union, intersection, membership, hashing, lookup, interview preparation
-```
+
-# Data Structures (Part III): Sets & the Collections Module
-## The "Set" Data Structure
-The `set` type describes an *unordered* collection of *unique* objects. It is useful for:
+# 数据结构(第三部分):集和集合模组
+## 集数据结构
+`set`(集)类是一个成员为*互不相同*的对象的*无序*集合。它在以下情况有用:
-- Filtering out "repeat" objects in a collection, producing only its unique members.
-- Quickly checking for membership, as a $\mathcal{O}(1)$ operation.
-- Efficiently comparing two sets of objects; e.g. if one set is a "subset" of another.
+- 过滤集合中“重复”的成员并仅仅返回其中不重复的成员。
+- 快速($\mathcal{O}(1)$)检查对象是否为成员。
+- 高效地对比两个集;如检查一个集是否为另外一个的“子集”(subset)。
-A set uses a "hashing" scheme for keeping track of its contents. Thus, like a dictionary's keys, a set can only store *immutable* objects so that its hashes will never become invalid. Unlike the other data structures that we have encountered, *there is no mechanism for retrieving an individual item from a set*. That is, there is no index or key that can be used to retrieve an individual member from a set.
+集使用“哈希”(hashing)算法来记录它的成员。因此,像词典的键一样,集只能储存*不可变*的对象来保证对象的哈希值不会无效。和我们遇到的其它数据结构不同,*你无法从集中获取单独的成员*。也就是说,没有任何索引或键可以用来获取集中的单个成员。
-Python's sets also support many familiar set-algebra operations, like taking the union or intersection of sets, as we will see below. For an exhaustive listing of the functions available to sets, please consult [the official documentation on sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset).
+Python的集也支持了常见的集合代数操作,如并集(union)或交集(intersection)运算,如下所见。你可以阅读[集的官方说明文档](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)来查看所有可用的集函数。
-### Creating a set
-You can initialize a set using the syntax: `{item1, item2, ...}`. Please note that this is distinct from the the dictionary-initialization syntax, which uses a colon to indicate key-value pairs:
+### 创建集
+你可以用以下语法初始化集:`{item1, item2, ...}`。请注意,这和使用冒号表达键值对的词典初始化语法不同:
```python
-# initializing a set containing various immutable objects
+# 初始化有着各种不可变对象的集
>>> {1, 3.4, "apple", False, (1, 2, 3)}
{False, 1, (1, 2, 3), 3.4, 'apple'}
```
-A set can be constructed using the generator-comprehension syntax:
+你可以使用生成器理解语法来创建一个集:
```python
-# initialization via set-comprehension
+# 使用集理解来初始化
>>> {i**2 for i in range(5) if i != 3}
{0, 1, 4, 16}
```
-And, like the `list`, `tuple`, and `dict` types, the `set` type can be used to construct a set from an iterable. Note that you must use `set()` if you want to create an empty set, using `{}` creates an empty *dictionary*:
+同时,和 `list`,`tuple`,和 `dict` 类型类似,`set` 类型可以接受可迭代物来创建集。请注意你必须使用 `set()` 来创建一个空集,因为 `{}` 会创建一个空*词典*:
```python
-# introducing the `set` type
+# 介绍 `set` 类型
>>> type({2, 4, 6})
set
-# using `set` to consume an iterable to construct a set
+# 使用 `set` 消耗一个可迭代物来创建集
>>> set(range(4))
{0, 1, 2, 3}
-# creating an empty set
->>> set() # specifying `{}` would create an empty *dictionary*
+# 创建空集
+>>> set() # 如果使用 `{}` 则会创造一个*词典*
set()
```
-Redundant items are "ignored" when constructing or adding to a set. Thus *constructing a set is a great way to extract the unique items from a collection*:
+在创建或往集里面添加内容时会“无视”重复的项目。所以说,*创建集是一个很棒的从集合中抽取独特对象的方法*:
```python
-# filter repeat-items from a collection by feeding it into a set
+# 通过输入到集中过滤集合中重复的对象
>>> x = [1, 2, 1, 2, 1, "moo", "moo"]
>>> set(x)
{1, 2, 'moo'}
@@ -73,94 +73,94 @@ Redundant items are "ignored" when constructing or adding to a set. Thus *constr
-**Reading Comprehension: Set Creation**
+**阅读理解:创建集**
-Use a set to find all of the unique letters in the string `"The cat in the hat"`. Ignore all non-letter characters and lowercase all letters.
+使用集来找到字符串 `"The cat in the hat"` 中所有的独特的字母。无视所有不是字母的字符,并将所有字母小写化。
-### Set operations
-Sets support membership-checking ($\mathcal{O}(1)$) along with iteration ($\mathcal{O}(n)$). Note that sets are unordered; thus the order of iteration is effectively random:
+### 集操作
+集支持成员检测为($\mathcal{O}(1)$)以及迭代($\mathcal{O}(n)$)。注意集是无序的,所以迭代顺序实际上是随机的:
```python
-# checking membership in a set
+# 检查集成员
>>> 2 in {1, 2, 3}
True
-# iterating over a set (the order of iteration is random)
+# 迭代集(迭代顺序是随机的)
>>> [i for i in {"a", "b", "c"}]
['b', 'c', 'a']
```
-Python also provides the set-theoretic operations of union, intersection, and the relations of set equality and set inclusion. These can be invoked using operator symbols or by calling functions on the set explicitly.
+Python也支持集合代数操作:并集(union),交集(intersectino),等值(equality),和子集(subset)关系。你可以通过操作符或通过显性调用集函数来进行这些操作。
-For an exhaustive list of the functions available to the set, please [refer to the official Python documentation](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset).
+请[查阅Python官方说明文档](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)来阅读集函数的完整列表。
```python
-# demonstrating set-comparison operations
+# 演示集对比操作
>>> x = {"a", "b", "c", "d"}
>>> y = {"a", "b", "e"}
-# union: items in x or y, or both
->>> x | y # or x.union(y)
+# 并集:在x或y或全部两个集当中的项目
+>>> x | y # 等值于 x.union(y)
{'a', 'b', 'c', 'd', 'e'}
-# intersection: items in both x and y
->>> x & y # or x.intersection(y)
+# 交集:在x和y中的项目
+>>> x & y # 等值于 x.intersection(y)
{'a', 'b'}
-# difference: items in x but not in y
->>> x - y # or x.difference(y)
+# 差:在x而不在y中的项目
+>>> x - y # 等值于 x.difference(y)
{'c', 'd'}
-# symmetric difference: in x or y, but not in both
->>> x ^ y # or x.symmetric_difference
+# 对称差:在x或y但不是全部两个的项目
+>>> x ^ y # 等值于 x.symmetric_difference(y)
{'c', 'd', 'e'}
-# check if set_1 is a superset of set_2
+# 检查set_1是否为set_2的超集(superset)
>>> {1, 2, 3, 4} >= {1, 2}
True
-# check if set_1 and set_2 are equivalent sets
+# 检查set_1和set_2是否为相同的集
>>> {1, 2, 3, 4} == {1, 2}
False
```
-A set is a *mutable* object; it can be updated after it was created:
+集是一个*可变*对象;你可以在创建后修改它:
```python
-# sets are mutable
+# 集是可变的
-# add a single member to `x`
+# 往 `x` 中添加一个成员
>>> x.add("dog")
-# update `x` by adding members of an iterable
+# 通过添加可迭代物中的成员来更新 `x`
>>> x.update([1, 2, 3])
-# remove a member of `x`
+# 删除 `x` 的一个成员
>>> x.remove("a")
>>> x
{1, 2, 3, 'b', 'c', 'd', 'dog'}
```
-Because it is mutable, a set cannot be used as a dictionary-key, nor can a set be a member of another set. Python provides an immutable version of the set, `frozenset`, which has all of the functions of a set other than those that mutate the set:
+因为集是可变的,它不能作为词典的键,也不能作为另外一个集的成员。Python提供了一个不可变版本的集,叫做 `frozenset`。它有着集所有除了修改集的操作函数:
```python
-# `frozenset` is an immutable version of a Python set
+# `frozenset` 是Python集的不可变版本
>>> frozenset(x)
frozenset({1, 2, 3, 'b', 'c', 'd', 'dog'})
```
-**Takeaway**:
+**经验**:
-Python's set is an unordered collection of unique, immutable objects. It is an excellent tool for extracting the unique members from a collection of items. The set provides $\mathcal{O}(1)$ membership-checking along with a suite of set-algebra operations for comparing sets. `frozenset` is an immutable version of the set.
+Python的集的成员为互不相同,不可变的对象的集合。它是从对象集合中获取不重复的成员的好方法。集提供了 $\mathcal{O}(1)$ 的成员检测以及一组对比集的集合代数操作。`frozenset` 是集的不可变版本。
-**Reading Comprehension: Set Comparisons**
+**阅读理解:对比集**
-Given the enrollment lists for class-A and class-B, find the students enrolled in both classes. Produce the result as a sorted list of names.
+设课A和课B的学生,寻找同时有着这两门课的同学名单。返回排序过的名字列表。
```python
>>> classA = ["Bohr", "Curie", "David", "Euler", "Fermi", "Feynman", "Gauss", "Heisenberg", "Noether"]
@@ -170,30 +170,30 @@ Given the enrollment lists for class-A and class-B, find the students enrolled i
-## The Collections Module
-Python provides a number of valuable, optimized data structures in its ["collections" module](https://docs.python.org/3/library/collections.html). It is recommended that the reader take some time to peruse this module. Here, we will briefly show off some of the utilities of its data structures.
+## collections模组
+Python在其[“collections”模组](https://docs.python.org/3/library/collections.html)提供一系列优化过的实用数据结构。本文建议读者花一些时间去细读该模组。我们将在这里快速展示其中包含的数据结构的用处。
-Refer to the [official documentation](https://docs.python.org/3/library/collections.html) for a complete listing of the functions available to these data structures.
+请查阅[官方说明文档](https://docs.python.org/3/library/collections.html)来阅读所有这些数据结构可用的函数。
### Named-Tuple
-A named tuple allows you to form a tuple whose members are named. Thus the user can access a member by name or via index. Otherwise the named tuple behaves just like a typical tuple. This facilitates clean, readable code.
+一个命名元组(namedtuple)允许你创建有名字的成员的元组。这样,你可以通过名字或者索引来访问其中的成员。除此之外命名元组和正常元组的行为完全一样。这将帮助你编写干净易读的代码。
-Suppose, for instance, you want to keep track of the 3D-position and time of an event. You can use a named-tuple so that each space and time coordinate can be referenced "by name". In this way, the reader doesn't have to keep in mind that element-3 of your tuple corresponds to time:
+比如说,假设你想要储存某事件的3D坐标以及时间,你可以使用命名元组来“根据名字”调用其空间和时间坐标。通过这个方式,代码的读者不需要记住元组的索引3代表着时间坐标这一设定:
```python
-# demonstrate the use of named tuple
+# 演示命名元组
>>> from collections import namedtuple
-# Define a tuple that holds a space-time coordinate.
-# Here we define the tuple to have four entries, named
-# 'x', 'y', 'z', and 't', in order.
+# 定义储存时空坐标的元组。
+# 我们如此顺序定义元组的四个成员,名字为
+# 'x','y','z',和 't'。
>>> space_time_coord = namedtuple("space_time_coord", ['x', 'y', 'z', 't'])
-# `r` is a particular space-time coordinate (an instance of our named tuple)
+# `r` 是某一个时空点(我们定义的命名元组的一个实例)
>>> r = space_time_coord(1.5, 2.3, 5.1, 100.2)
->>> r.x # access the x coordinate "by name"; this is more descriptive than `r[0]`
+>>> r.x # “通过名字”访问x坐标;这比 `r[0]` 更加易懂
1.5
>>> r.y
@@ -205,7 +205,7 @@ Suppose, for instance, you want to keep track of the 3D-position and time of an
>>> r.t
100.2
-# you can also access contents by indexing/slicing
+# 你也可以通过索引/切片来访问其内容
>>> r[3]
100.2
@@ -215,52 +215,51 @@ Suppose, for instance, you want to keep track of the 3D-position and time of an
-### Default Dictionary
-A default dictionary allows you to specify a Python function, $f$ that will be used as a "default value" for that dictionary. The default value will be whatever $f()$ returns. That is, whenever you try to access a key that does not exist in the dictionary, instead of raising `KeyError`, the mapping $key \rightarrow f()$ will be created in the dictionary:
+### 默认词典
+默认词典(defaultdict)允许你提供一个Python函数 $f$ 来作为该词典的“默认值”,其默认值为 $f()$ 返回的值。也就是说,每当你试图访问在词典中不存在的键时,词典会创建 $key \rightarrow f()$ 的对应关系而不会导致 `KeyError`:
```python
-# demonstrate the behavior of the `defaultdict`
+# 演示 `defaultdict` 的行为
>>> from collections import defaultdict
->>> example_default_dict = defaultdict(list) # will map any missing key to `list()`
->>> example_default_dict # an empty default dictionary
+>>> example_default_dict = defaultdict(list) # 会将任何不存在的键对应到 `list()`
+>>> example_default_dict # 空默认词典
defaultdict(list, {})
-# "apple" is not a key, so the default mapping "apple" -> list() is created
-# and this value is returned
+# "apple" 并不是一个存在的键,所以词典将创建默认对应关系 "apple" -> list()
+# 并返回对应的值
>>> example_default_dict["apple"]
[]
-# this mapping now exists in the dictionary
->>> example_default_dict
+# 现在这个对应关系在词典中存在
+>>> example_default_dict
defaultdict(list, {'apple': []})
```
-Suppose you want to use a dictionary as a grade book, which maps $name \rightarrow grades$. With a standard dictionary, you have to worry about encountering a student for the first time:
+假设你想要将一个词典当作成绩簿来使用,其对应关系为 $名字 \rightarrow 成绩(多个)$。在使用标准词典时,你会需要担心第一次输入某学生成绩的情况:
```python
-# using a vanilla dictionary to store: name -> list of grades
-student = "Ryan"
-grade = 52 # I failed the test...
+# 使用标准词典来储存:名字 -> 成绩列表
+student = "Ryan" # 译者注:这是原作者的名字
+grade = 52 # 我不合格...
-# standard dictionary usage
+# 标准词典的用法
gradebook = {}
-# if student isn't in the gradebook, enter that student
-# along with an empty list as the grades
+# 如果学生不在成绩簿中,将学生先作为空列表输入
if student not in gradebook:
gradebook[student] = []
-gradebook[student].append(grade) # append the grade to that student's list of grades
+gradebook[student].append(grade) # 在列表最后添加学生的成绩
```
-The default dictionary's behavior exactly accommodates this initialization process (when providing `list` as the initialization function):
+默认词典的行为(当你向初始化函数提供 `list` 时)完全代替了以上的初始化过程:
```python
-# using a default dictionary to store: name -> list of grades
+# 使用默认词典来储存:名字 -> 成绩列表
>>> gradebook = defaultdict(list)
-# Because "Susan" doesn't exist in the dictionary
-# `list()` creates an empty list, as a default value,
-# which we can immediately append her grade to
+# 因为 "Susan" 在词典中并不存在
+# `list()` 创建一个空列表来作为默认值
+# 然后我们可以立刻向其添加她的成绩
>>> gradebook["Susan"].append(84)
>>> gradebook
@@ -269,58 +268,58 @@ defaultdict(list, {'Susan': [84]})
-### Counter
-Python's counter data structure is designed for tallying the unique objects that it encounters. It essentially creates a dictionary that maps: $obj \rightarrow count$. Suppose you want to study the distribution of words used in a body of text; counter is perfect for this application:
+### 计数器
+Python的计数器(counter)数据结构旨在计算它遇到的独特的对象数。基本上,它就是创建了一个对应 $对象 \rightarrow 遭遇次数$ 的词典。假设你想要了解在某文本中单词的分布,计数器是完美的解决方案:
```python
-# demonstrate the `Counter` data structure
+# 演示 `Counter` 数据结构
>>> from collections import Counter
-# Note: We will "normalize" our text by making it all lowercase.
-# We will then split the string by its spaces, storing the resulting
-# tokens in a list. For real text, we would also want to remove punctuation
+# 注:我们将会“标准化“我们的文本,使其全部都为小写。
+# 我们将会根据空格区分单个单词,并将得到的单词存在列表中
+# 如果我们在使用真正的文本,我们也会想要删除标点符号
>>> text_1 = "The cat in the hat"
>>> text_1 = text_1.lower().split()
>>> text_1
['the', 'cat', 'in', 'the', 'hat']
->>> word_distr = Counter(text_1) # tally the unique objects in `text_1`
+>>> word_distr = Counter(text_1) # 数 `text_1` 中独特对象的出现次数
>>> word_distr
Counter({'cat': 1, 'hat': 1, 'in': 1, 'the': 2})
-# feed additional items to the counter by "update"
+# 利用“update”来输入更多的对象
>>> text_2 = "The apple in the tree"
>>> text_2 = text_2.lower().split()
>>> word_distr.update(text_2)
>>> word_distr
Counter({'apple': 1, 'cat': 1, 'hat': 1, 'in': 2, 'the': 4, 'tree': 1})
-# get the top-2 most common words, along with their counts
+# 获取2个最常见的单词以及它们的出现次数
>>> word_distr.most_common(2)
[('the', 4), ('in', 2)]
-# get the count for the word "tree"
+# 获取单词“tree”的出现次数
>>> word_distr["tree"]
1
```
-`Counter` accepts any iterable of immutable objects:
+`Counter` 接受任何成员为不可变对象的可迭代物:
```python
>>> Counter([0, 0, "moo", (None, None), (None, None), (None, None)])
Counter({(None, None): 3, 0: 2, 'moo': 1})
```
-Refer to the [official documentation](https://docs.python.org/3/library/collections.html#counter-objects) for a complete listing of all the nice functions that `Counter` has access to.
+请查阅[官方说明文档](https://docs.python.org/3/library/collections.html#counter-objects)来阅读 `Counter` 的棒棒的可用函数。
-### The deque
-Like the list, Python's deque is a mutable, sequential data structure. What distinguishes the deque is that:
+### 双队列
+像列表一样,Python的双队列(deque)是一个可变的序列性数据结构。双队列不同的点在于:
- - Mutating either the beginning or the end of a deque is $\mathcal{O}(1)$, whereas mutating the beginning of a list is $\mathcal{O}(n)$. As such, the deque has unique functions to take advantage of this, like `appendleft`.
- - The downside of the preceding feature is that *accessing items near the middle of the deque is* $\mathcal{O}(n)$, whereas it is $\mathcal{O}(1)$ for lists and tuples.
+ - 修改双队列的开头或者结尾都是 $\mathcal{O}(1)$,而修改列表开头是 $\mathcal{O}(n)$。因此,双队列有着独特的函数来利用这一优势,如 `appendleft`。
+ - 以上功能的坏处在于*获取双队列靠近中间的对象是* $\mathcal{O}(n)$,而列表和元组是 $\mathcal{O}(1)$。
-A complete rundown of the deque's functionality can be found [here](https://docs.python.org/3/library/collections.html#deque-objects).
+你可以在[这里](https://docs.python.org/3/library/collections.html#deque-objects)找到双列表的完整功能。
-The deque is included in Python's `collections` module, and thus must be imported:
+双列表属于Python `collections` 模组的成员,因此你需要导入它:
```python
>>> from collections import deque
>>> my_deque = deque([1,2,3])
@@ -330,21 +329,21 @@ deque([0, 1, 2, 3])
```
-## Links to Official Documentation
+## 官方说明文档链接
-- [Sets and frozen sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
- - [Tutorial on sets](https://docs.python.org/3/tutorial/datastructures.html#sets)
-- [The collections module](https://docs.python.org/3/library/collections.html)
+- [集和冻集](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
+ - [集教程](https://docs.python.org/3/tutorial/datastructures.html#sets)
+- [collections模组](https://docs.python.org/3/library/collections.html)
-## Reading Comprehension Solutions
+## 阅读理解答案
-**Set Creation: Solution**
+**创建集:解**
-Use a set to find all of the unique letters in the string `"The cat in the hat"`. Ignore all non-letter characters and lowercase all letters.
+使用集来找到字符串 `"The cat in the hat"` 中所有的独特的字母。无视所有不是字母的字符,并将所有字母小写化。
-We can use the built-in string functions [isalpha](https://docs.python.org/3/library/stdtypes.html#str.isalpha) and [lower](https://docs.python.org/3/library/stdtypes.html#str.lower) to filter out non-letter characters, and to lowercase the letters.
+我们可以使用内置的字符串函数[isalpha](https://docs.python.org/3/library/stdtypes.html#str.isalpha)和[lower](https://docs.python.org/3/library/stdtypes.html#str.lower)来过滤非字母字符并小写化所有字母。
```python
>>> sentence = "The cat in the hat"
@@ -354,15 +353,15 @@ We can use the built-in string functions [isalpha](https://docs.python.org/3/lib
-**Set Comparisons: Solution**
+**对比集:解**
-Given the roster for class-A and class-B, find the students enrolled in both classes. Produce the result as a sorted list.
+根据课A和课B的名单表,找到同时在两个班的学生名单。返回排序过的名字列表。
```python
>>> classA = ["Bohr", "Curie", "David", "Euler", "Gauss", "Heisenberg", "Noether"]
>>> classB = ["Bohm", "Bohr", "Einstein", "Fermi", "Gauss", "Hopper", "Montalcini"]
```
-We can find the entries common to both lists by constructing sets from them, and then taking the intersection of those sets. The result is a set, which is an iterable. Thus it can be fed to the built-in function [sorted](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#Functions-that-act-on-iterables), to produce a sorted list of names.
+我们可以通过使用这两个列表创建集然后求交集来找出两个列表通用的名字。结果为一个集,而集是一种可迭代物。因此我们可以将其输入进内置的函数[sorted](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#操作可迭代物的函数)并返回排序过的名字列表。
```python
>>> sorted(set(classA) & set(classB))
diff --git a/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md b/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md
index 5333500..d74dbb4 100644
--- a/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md
+++ b/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md
@@ -4,116 +4,116 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Introduction to Dictionaries, Difficulty: Medium, Category: Section
:keywords: dictionary, complexity, key, value, iteration, get item, hashing, lookup, interview preparation
-```
+
-# Data Structures (Part II): Dictionaries
-Python's dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects. **Each key must map to exactly one value**, meaning that a key must be unique.
+# 数据结构(第二部分):词典
+Python的词典(dictionary)允许你储存键值对(key-value pair),然后通过提供键来快速地获取其对应的值。具体来讲,你通过描述从键到值的单向对应关系来创建词典。**每个键应该只对应一个值**,也就是说每个键都应该是唯一的。
-Let's create the following mapping of grocery-to-price:
+让我们来创建以下从食物到价格的对应关系:
-- "cheese" $\rightarrow$ 2.53,
-- "milk" $\rightarrow$ 3.40,
+- "cheese" $\rightarrow$ 2.53,
+- "milk" $\rightarrow$ 3.40,
- "frozen pizza" $\rightarrow$ 8.01
```python
-# use a dictionary to map groceries to prices: item-name -> price
+# 使用一个词典来将食物来对应价格:名字 -> 价格
>>> items_to_prices = {"cheese": 2.53, "milk": 3.40, "frozen pizza": 8.01}
-# looking up the price of "frozen pizza"
+# 查看 "frozen pizza" 的价格
>>> items_to_prices["frozen pizza"]
8.01
```
-Python's dictionary is a shining star among its data structures; it is compact, fast, versatile, and extremely useful. It can be used to create a wide variety of mappings.
+Python的词典是其数据结构中一颗闪耀的星;它紧凑,高效,通用,并非常有用。你可以用它来创建多种多样的对应关系。
```python
-# keep track of whether or not a 3D coordinate fell into some region in space
-# map (x, y, z) coordinates to "is in a region": (x, y, z) -> True/False
+# 记录某3D坐标是否处于空间中某区域之中
+# 将 (x, y, z) 坐标对应到“是否在区域中”:(x, y, z) -> True/False
>>> point_to_region = {(0.1, 2.2, 3):False, (-10., 0, 4.5):True, (4.3, 1.0, 9.5):False}
>>> point_to_region[(-10., 0, 4.5)]
True
-# map student-name to exam scores: name -> scores
+# 将学生名字对应到考试成绩中:名字 -> 成绩
>>> name_to_scores = {"Ryan S": [65, 50, 80], "Nick S": [100, 99, 90]}
>>> name_to_scores["Ryan S"]
[65, 50, 80]
```
- It is important to note outright that the time it takes for dictionary to take a key and retrieve a value *does not depend on the size of the dictionary.* That is the complexity for a dictionary look-up is $\mathcal{O}(1)$! It accomplishes this by making use of a technique known as [hashing](https://en.wikipedia.org/wiki/Hash_function).
+我们应该立刻指出:在词典中查找某键对应的值的速度*并不会根据词典大小改变。*也就是说,词典查找的复杂度为 $\mathcal{O}(1)$!它通过一个知名的[哈希算法](https://en.wikipedia.org/wiki/Hash_function)技巧来达到这一点。
-These are all instances of the built-in `dict` type:
+以下为所有内置 `dict` 类型的实例:
```python
>>> type(items_to_prices)
dict
```
-We will be discussing the essentials of the dictionary. It is highly recommended that you refer to the official Python documentation for a [complete rundown of all the functions available to the dictionary](https://docs.python.org/3/library/stdtypes.html#dict).
+我们会在下文讨论词典的基础。本文强烈建议你阅读Python官方说明文档来查看[所有词典可用的函数](https://docs.python.org/3/library/stdtypes.html#dict).
-## Dictionary Basics
-### Constructing a dictionary
-A nice syntax for creating a dictionary is to specify key-value pairs inside "curly braces": `{key1:value1, key2:value2, ...}`. As an example, let's construct a dictionary that maps types of foods to "fruit" or "vegetable". We'll start by mapping "apple" to "fruit", and "carrot" to "vegetable"
+## 词典基础
+### 创建词典
+你可以通过在“花括号”中输入键值对来创建词典:`{key1:value1, key2:value2, ...}`。作为范例,让我们创建一个将食物名字对应到 "fruit" 或 "vegetable" 的词典吧。我们首先将 "apple" 对应到 "fruit","carrot" 对应到 "vegetable"
```python
-# use `{key1:value1, key2:value2, ...} to create a dictionary that maps:
+# 使用 `{key1:value1, key2:value2, ...}` 来创建词典:
# "apple" -> "fruit"
# "carrot" -> "vegetable
->>> fruit_or_veggie = {"apple":"fruit", "carrot":"vegetable"}
+>>> fruit_or_veggie = {"apple":"fruit", "carrot":"vegetable"}
-# create an empty dictionary
+# 创建空词典
>>> {}
{}
```
-You can also use `dict` as a constructor to create the dictionary. It can be fed an iterable of key-value pairs, each of which is packed in a sequence, such as a tuple.
+你也可以使用 `dict` 来作为构造器来创建词典。你可以向其输入存有键值对(键值对由如元组的序列表达)的可迭代物。
```python
-# use `dict` to create a dictionary that maps:
+# 使用 `dict` 来创建词典:
# "apple" -> "fruit"
# "carrot" -> "vegetable
>>> fruit_or_veggie = dict([("apple", "fruit"), ("carrot", "vegetable")])
-# use `dict` to create an empty dictionary:
+# 使用 `dict` 来创建空词典
>>> dict()
{}
```
-Lastly, Python also supports a dictionary-comprehension syntax, which mirrors the generator/list comprehension syntax covered earlier in this module:
+最后,Python也支持词典理解语法,其与本模组之前讨论的生成器/列表理解语法类似:
```
{key:value for key, value in [if bool()]}
```
```python
-# use the 'dictionary comprehension' syntax to create a dictionary that maps:
+# 使用“词典理解”语法来创建词典
# "apple" -> "fruit"
# "carrot" -> "vegetable
>>> {k:v for k,v in [("apple", "fruit"), ("carrot", "vegetable")]}
{'apple': 'fruit', 'carrot': 'vegetable'}
```
-### Retrieving a value, given a key
-Now we can use this dictionary to "look up" if an item is a fruit or a veggie. Dictionaries support the same square-bracket "get-item" syntax as a list/tuple, but here a valid key is used as the index:
+### 返回键对应的值
+现在我们可以使用词典来“查找”某项目是水果还是蔬菜。词典支持和列表/元组一样的方括号“获取项目”语法,但与其使用索引我们将使用一个合法的键:
```python
-# get the value associated with the key "apple"
+# 获取键 "apple" 对应的值
>>> fruit_or_veggie["apple"]
"fruit"
```
-`KeyError` will be raised if you try to look-up a key that doesn't exist:
+尝试查找不存在的键会导致 `KeyError`:
```python
-# "grape" hasn't been specified as a key
+# "grape" 并没有作为键被定义
>>> fruit_or_veggie["grape"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
@@ -123,19 +123,19 @@ KeyError Traceback (most recent call last)
KeyError: 'grape'
```
-### Adding more key-value mappings
-Once created, a dictionary can have a new key-value pair be "set" using `my_dict[new_key] = new_value`:
+### 添加额外的键值对
+在词典创建后,你可以通过 `my_dict[new_key] = new_value` 在其中设定额外的的键值对:
```python
-# set the mapping "banana" -> "fruit"
+# 设定对应 "banana" -> "fruit"
>>> fruit_or_veggie["banana"] = "fruit"
>>> fruit_or_veggie
{'apple': 'fruit', 'banana': 'fruit', 'carrot': 'vegetable'}
```
-If the key already exists, the mapping for that key will simply be updated.
+如果键已经存在的话,那该键对应的值将被更新。
-The `update` function can be used to add multiple key-value pairs at once. This function can be passed another dictionary or an iterable of key-value sequences
+你可以使用 `update` 函数来一次性添加多个键值对。该函数接受另外一个词典或成员为键值对序列的可迭代物
```python
-# adding multiple key-value pairs to the dictionary
+# 向词典添加多个键值对
>>> fruit_or_veggie.update([("grape", "fruit"), ("onion", "vegetable")])
>>> fruit_or_veggie
{'apple': 'fruit',
@@ -148,19 +148,20 @@ The `update` function can be used to add multiple key-value pairs at once. This
-**Reading Comprehension: Dictionary Basics**
+**阅读理解:词典基础**
+
+设含有学生名的元组 `("Ashley", "David", "Edward", "Zoe")` 以及他们对应的考试成绩 `(0.92, 0.72, 0.88, 0.77)`,创建一个词典来对应:名字 $\rightarrow$ 成绩。然后,将Zoe的成绩更新为 `.79`。最后添加一个新学生Ryan,其成绩为0.34。
-Given the tuple of student names `("Ashley", "David", "Edward", "Zoe")`, and their corresponding exam grades `(0.92, 0.72, 0.88, 0.77)`, create a dictionary that maps: name $\rightarrow$ grade. Then, update Zoe's grade to `.79`. Lastly, add a new student, Ryan, whose grade is 0.34.
+译者注:原作者名为Ryan,是位自黑达人。
-## What Can a Dictionary Store?
-Although the preceding example only involves a mappings from strings to strings, *the keys and values of a dictionary can be heterogeneous in type*:
+## 词典可以储存什么?
+虽然前文的例子中仅仅将字符串对应字符串,但是*词典的键和值的类型可以相异*:
```python
-# demonstrates the wide variety of object types that can be used as
-# keys and values in a dictionary
+# 演示词典可以使用的多种多样的键值类型
>>> example_dict = {-1:10, "moo":True, (1, 2):print, 3.4:"cow", False:[]}
>>> example_dict[-1]
10
@@ -178,32 +179,32 @@ True
[]
```
-To be specific, a dictionary's contents are dictated by the following rules:
+具体来讲,词典应遵循以下规则:
-- A dictionary *key* must be an *immutable* object (more precisely, it must be [hashable](https://docs.python.org/3/glossary.html#term-hashable); don't worry about this detail).
-- A dictionary *value* can be any object (even the dictionary itself! Try this, it's cool!)
+- 词典的*键*必须是*不可变*的对象(更加精确地讲,它必须是[可哈希](https://docs.python.org/3/glossary.html#term-hashable)(hashable)的;不要太在意这个细节)。
+- 词典的*值*可以是任何对象(甚至可以是同一个词典!试试看,这挺酷的!)
-**Recall**:
+**回忆**:
-A mutable object can be changed after it is created. An immutable object cannot be changed.
+可变对象在被创建后是可以被修改的。不可变对象则不能被修改。
-Thus valid keys can be the following types:
+所以合法的键可以是以下类型:
+
+ - 数字(整数,浮点数,复数)
+ - 字符串
+ - 元组(但元组中的成员也必须是不可变对象)
+ - 布尔值
+ - [冻集](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#集操作)(frozenset)对象
+
+使用可变对象作为键的问题在于该对象在作为键使用*之后*可以被改变。因此,词典会需要通过某种方法“检测”到这个变化并为变化后的键重新创建它的“查找方式”。相比之下,值可以是可变对象,因为值对象的细节并不影响词典如何查找该值。
- - numbers (integers, floating-point numbers, complex numbers)
- - strings
- - tuples (if the tuple contains anything, it must be other immutable objects)
- - boolean values
- - [frozenset](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#Set-operations) objects
-
-Trying to use a mutable object as a key is problematic since that object could be changed *after* it was already used as a key. Thus the dictionary would have to "detect" this change and recreate its "lookup scheme" for the changed key. Values, on the other hand, can be mutable because the details of a given value-object have no impact on how the dictionary retrieves it.
-
-In accordance with this discussion will get a `TypeError` if you try to use a list as a key, since lists are mutable:
+如上所述,如果你试图使用列表来作为键,你会收到一个 `TypeError`,因为列表是可变的:
```python
-# trying to use a list as a key
-# this raises an error because lists are mutable
+# 试图将列表作为键使用
+# 因为列表是可变的,这会报错
>>> bad_dict = {[]:1}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
@@ -213,25 +214,24 @@ TypeError Traceback (most recent call last)
TypeError: unhashable type: 'list'
```
-### Numerical Precision & Dictionary Keys
-Care must be taken when using floating-point numbers as a key in a dictionary, [due to its limited numerical precision](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Understanding-Numerical-Precision). For the same reason that you ought not rely on two floats being equal, you should not assume that two floats will produce the same hash, when stored as a key:
+### 数字精度和词典键
+在使用浮点数作为词典键时需小心,因为浮点数的[精度有限](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#理解数字精度)。和你不应该检查两个浮点数是否完全相同的原因一样,你不能保证两个浮点数作为键时会有相同的哈希值:
```python
-# the folly of using a floating-point number as a key
-# in a dictionary
+# 将浮点数作为词典键使用导致的尴尬情况
>>> x = {}
>>> x[(0.1 + 0.1 + 0.1) - 0.3] = "apple"
>>> x[0.0]
KeyError: 0
```
-An acceptable way of accommodating the use of a float as a key, depending on the use case, is to first round the floating point number to normalize it to a lower precision:
+根据使用情况,一种可以接受的使用浮点数作为值的方法是先将浮点数四舍五入到一个更低的精度:
```python
-# rounding a float before using it as a key
+# 现将浮点数四舍五入再将其用为键
>>> x = {}
-# round the float to its 2nd decimal place
+# 将浮点数四舍五入到小数点后第二位
>>> float_key = round((0.1 + 0.1 + 0.1) - 0.3, 2)
>>> x[float_key] = "apple"
>> x[0.0]
@@ -240,78 +240,78 @@ An acceptable way of accommodating the use of a float as a key, depending on the
-**Takeaway**:
+**经验**:
-A dictionary key must be an immutable object. A dictionary value can be any object.
+词典的键必须是不可变对象。词典的值可以是任何对象。
-### Inspecting a Dictionary
-The dictionary provides tooling for inspecting and iterating over its keys and values. We will use the following dictionary for our examples:
+### 检查词典
+词典提供了一些检查和迭代其键和值的工具。我们在范例中将会使用以下词典:
```python
>>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"}
```
-**Inspecting a dictionary's keys**
+**检查词典的键**
-The dictionary itself can be used to iterate over its keys:
+你可以直接使用词典本身来迭代它的键:
```python
-# iterating over a dictionary produces its keys
+# 迭代词典会迭代它的键
>>> [i for i in example_dict]
['key1', 'key2', 'key3']
```
-You can also use the dictionary to test for membership among its keys:
+你也可以使用词典本身来检测某对象是否为它的键:
```python
-# checking if an object is among a dictionary's keys
+# 检查某对象是否是词典的键
>>> "key3" in example_dict
True
-# you *cannot* use this to check for membership among its valus
+# 你*不能*用这个方法检查词典的值
>>> "value3" in example_dict
False
```
-`len` counts the number of keys in the dictionary:
+`len` 会返回词典有多少个键:
```python
>>> len(example_dict)
3
```
-`example_dict.keys()` also returns an iterable over the dictionary's keys, and thus can be used to exactly the same effect as the dictionary itself in these preceding examples.
+`example_dict.keys()` 也会返回一个词典键的可迭代物。因此它可以达到和之前范例直接使用词典一样的效果。
-**Inspecting a dictionary's values**
+**检查词典的值**
-`example_dict.values()` can be iterated over to produce that dictionary's values:
+迭代 `example_dict.values()` 会提供词典的值:
```python
-# iterating over a dictionary's values
+# 迭代词典的值
>>> [i for i in example_dict.values()]
['value1', 'value2', 'value3']
```
-You can also use this to test for membership among the dictionary's values:
+你也可以使用这个函数来检查某对象是否为词典的值:
```python
-# checking if an object is among a dictionary's values
+# 检查某对象是否为词典的值
>>> "value1" in example_dict.values()
True
```
-**Inspecting a dictionary's key-value pairs**
+**检查词典的键值对**
-`example_dict.items()` can be iterated over to produce that dictionary's key-value pairs (which are packed into tuples):
+迭代 `example_dict.items()` 会返回词典的键值对(它们被打包在元组中):
```python
-# iterating over a dictionary produces its keys
+# 迭代词典的items会返回它的键值对
>>> [i for i in example_dict.items()]
[('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]
```
-You can also use this to test for membership among the dictionary's key-value pairs:
+你也可以用这个函数来检测某对象是否为词典的键值对:
```python
-# checking if a key-value pair exists in a dictionary
+# 检查某对象是否为词典的键值对
>>> ('key1', 'value1') in example_dict.items()
True
```
@@ -319,52 +319,52 @@ True
-**Reading Comprehension: Inverting a Dictionary**
+**阅读理解:反向词典**
-Write a function that inverts a dictionary. For example, if you were given `x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}`, you would produce the dictionary `inverted_x = {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}`.
+编写一个函数来将词典反向。比如说,如果函数收到 `x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}`,那你应返回词典 `inverted_x = {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}`。
-**Reading Comprehension: Inspecting a Dictionary**
+**阅读理解:检查词典**
-Assume we are working with a dictionary whose values are all *unique* numbers. Write a function that returns the *key* that maps to the *largest* value in the dictionary.
+假设我们收到一个值为*互不相同*的数字的词典,编写一个返回对应词典中*最大*值的*键*的函数。
-Next, generalize your solution for a dictionary whose values are not necessarily unique. Return a tuple of all of the keys that map to that max value.
+然后,修改你的函数来处理值可能重复值的词典。返回包含所有对应最大值的键的元组。
-### Time Complexities of the Dictionary's Functions
-In addition to being flexible and versatile, the dictionary's functions manage to be quite efficient as well. The following is a summary of the time complexities associated with various common operations using a dictionary (according to its implementation in CPython) - note all the $\mathcal{O}(1)$ operations!
+### 词典函数的时间复杂性
+除了灵活和通用之外,词典的函数也相对高效。以下为词典常见操作(在CPython实现中)的时间复杂性——请注意 $\mathcal{O}(1)$ 操作的数量!
-Let `example_dict` represent a dictionary with $n$ key-value pair mappings.
+设 `example_dict` 为有 $n$ 个键值对的词典。
-The following are $\mathcal{O}(1)$ operations:
+以下为 $\mathcal{O}(1)$ 的操作:
-- Return the number of keys in the dictionary: `len(example_dict)`
-- Check if the key is in the dictionary, and return the value if it is: `example_dict[key]`
-- Set a key-value mapping: `example_dict[key] = value`
-- Check if an object is among the dictionary's keys: `obj in example_dict`
-- Check if a pair of objects are among the dictionary's key-value pairs: `(obj1, obj2) in example_dict.items()`
+- 返回词典键的数量:`len(example_dict)`
+- 检查某对象是否为词典的键,如果是的话返回它对应的值:`example_dict[key]`
+- 设定一个键值对:`example_dict[key] = value`
+- 检查某对象是否为词典的键:`obj in example_dict`
+- 检查某对对象是否为词典的键值对:`(obj1, obj2) in example_dict.items()`
-The following are $\mathcal{O}(n)$ operations:
+以下为 $\mathcal{O}(n)$ 的操作:
-- Check if an object is among the dictionary's values: `obj in example_dict.values()`
-- Iterate over the dictionary's keys/values/key-value pairs
+- 检查某对象是否为词典的值:`obj in example_dict.values()`
+- 迭代词典所有的键/值/键值对
-### Are Dictionaries Ordered? A Word of Warning
-Unlike Python's sequences, the dictionary has no inherent ordering... that is, until Python 3.6 came out.
+### 词典是否有序?一句警告
+和Python的序列不同的是,词典没有任何内在的顺序...但是这是在Python 3.6前的历史了。
-Prior to Python 3.6, a dictionary had no ordering associated with it. If you iterated over a dictionary's keys, values, or key-value pairs, you had no guarantee about the *order* in which these items would be produced. `[i for i in example_dict]` could produce a list of keys with different ordering each time the code was run; you were only guaranteed that the list would contain all of the dictionary's keys:
+在Python 3.6之前,词典并没有任何顺序。如果你迭代一个词典的键,值,或键值对,你不会得到任何*顺序*的保证。`[i for i in example_dict]` 可能在每次运行时返回顺序不同的键列表;你唯一得到的保证是列表会包含词典所有的键:
```python
-# in Python 3.5 and earlier, dictionaries were unordered
+# 在Python 3.5和之前,词典是无序的
>>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"}
-# this can produce lists with different orders
+# 这可能会返回排序不同的列表
>>> [i for i in example_dict]
["key1", "key3", "key2"]
@@ -377,65 +377,63 @@ Prior to Python 3.6, a dictionary had no ordering associated with it. If you ite
...
```
-The dictionary was [reimplemented in Python 3.6](https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation) so that it will consume roughly 25% less memory than before (which is a big deal!). The catch is that this new implementation entails that the dictionary's various iterables (e.g. `dict.keys()`, `dict.values()`, `dict.items()`) will always yield their items according to the order in which they were added to the dictionary.
+词典在[Python 3.6中重新实现](https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation),使得它相比以前会少用大约25%的内存(这是一个很大的提升!)。随之而来的变化就是新的实现导致了词典的各种可迭代物(如 `dict.keys()`,`dict.values()`,`dict.items()`)每次都会根据添加到词典中的顺序返回对象。
```python
-# in Python 3.6 and beyond dictionaries are ordered according to the order in
-# which key-value pairs were added to the dictionary by the user
+# 在Python 3.6和之后,词典根据键值对添加的顺序来排序
>>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"}
-# this will always produce the same ordering of keys
+# 这永远都会返回一样顺序的键
>>> [i for i in example_dict]
["key1", "key2", "key3"]
```
-This is great, right? Wrong! If you write code in Python 3.6 that relies on the fact that dictionaries are ordered, your algorithm will almost certainly produce the wrong results if you run it using Python 3.5 or earlier! Worst of all, it very unlikely that this will raise any error in your code so the bug will persist silently - this is very tough to catch!
+这很棒,对吧?不对!如果你在Python 3.6中编写基于词典成员顺序的代码,那么你的算法在Python 3.5和以前几乎一定会导致错误的结果!最差的一点是,这很可能在你的代码中根本不报错,所以这个bug会静默地持续下去——这很难抓到!
-**Unless you make explicit that your code is incompatible with versions of Python prior to Python 3.6, write your code as if the dictionary is unordered!**
+**如果你没有明显标记你的代码和Python 3.6之前的版本不兼容,编写代码的时候假装词典并没有顺序!**
-If you do want to use an ordered dictionary, make use of `collections.OrderedDict`, which behaves like just like the standard dictionary but is guaranteed to maintain ordering regardless of what version of Python you are using.
+如果你真的想要需要一个顺序的词典,使用 `collections.OrderedDict`。它的行为和正常的词典一模一样,但它不管在什么Python版本都保证成员顺序。
```python
from collections import OrderedDict
>>> ordered = OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
-# this will always produce the same result, regardless of what
-# version of Python is being used
+# 这永远都会返回相同的结果,不论Python版本
>>> [i for i in ordered]
["key1", "key2", "key3"]
```
-**Takeaway**:
+**经验**:
-No matter what version of Python you are using, write your code as if the Python dictionary is unordered. If you do want to use an ordered dictionary, your code should make use of `collections.OrderedDict`.
+不管你在用什么Python版本,在编写代码的时候假装Python词典是无序的。如果你真的想要一个有序的词典,你的代码应该使用 `collections.OrderedDict`。
-## Links to Official Documentation
+## 官方说明文档链接
-- [Dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
- - [Dictionaries tutorial](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
-- [Definition of 'hashable'](https://docs.python.org/3/glossary.html#term-hashable)
-- [Dictionary view objects](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects)
+- [词典](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
+ - [词典教程](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
+- [“可哈希”的定义](https://docs.python.org/3/glossary.html#term-hashable)
+- [词典视阈对象](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects)(dictionary view objects)
-## Reading Comprehension Solutions
+## 阅读理解答案
-**Dictionary Basics: Solutions**
+**词典基础:解**
-Given the tuple of student names `(Ashley, David, Edward, Zoe)`, and their corresponding exam grades `(0.92, 0.72, 0.88, 0.77)`, create a dictionary that maps: name $\rightarrow$ grade.
+设包含学生名字的元组 `(Ashley, David, Edward, Zoe)` 以及对应的成绩 `(0.92, 0.72, 0.88, 0.77)`,创建一个词典:name $\rightarrow$ grade。
-Then, update Zoe's grade to `.79`. Lastly, add a new student, Ryan, whose grade is 0.34.
+然后,将Zoe的成绩更新为 `.79`。最后,添加一个新学生Ryan,其成绩为 0.34。
```python
names = ("Ashley", "David", "Edward", "Zoe")
scores = (0.92, 0.72, 0.88, 0.77)
```
-Here is a basic, but verbose solution. It is too long and its logic is complicated by the use of `index`.
+这是一个简单但冗长的解法。它太长,且其逻辑使因为使用了 `index` 而没必要地复杂化了。
```python
# basic solution for creating `grades`
@@ -446,24 +444,24 @@ for index in range(len(names)):
grades[name] = value
```
-You should make use of the function [zip](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Itertools.html#zip) to pair the names and scores together in an iterable, and create the dictionary using a comprehension expression.
+你应该使用函数[zip](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Itertools.html#zip)来将名字和成绩打包到一个可迭代物中,并利用理解表达式来创建词典。
```python
-# much better solution for creating `grades`
+# 好很多的创建 `grades` 的方式
grades = {student:value for student, value in zip(names, scores)}
-# updating Zoe's grade
+# 更新Zoe的成绩
grades["Zoe"] = 0.79
-# adding Ryan's grade
+# 添加Ryan的成绩
grades["Ryan"] = 0.34
```
-**Inverting a Dictionary: Solution**
+**反向词典:解**
```python
-# simple solution: using a for-loop
+# 简单解:使用for循环
x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
inverted_x = {}
for key, value in x.items():
@@ -471,21 +469,21 @@ for key, value in x.items():
```
```python
-# better solution: using a dictionary-comprehension
+# 更好的解:使用词典理解
inverted_x = {value:key for key, value in x.items()}
```
-**Inspecting a Dictionary: Solution**
+**检查词典:解**
-Assume we are working with a dictionary whose values are all *unique* numbers. Write a function that returns the key that maps to the *largest* value in the dictionary.
+假设我们收到一个值为*互不相同*的数字的词典,编写一个返回对应词典中*最大*值的键的函数。
-The solution that you should be able to arrive at is:
+你应该能够写出的解为:
```python
# solution
-def max_key(x):
+def max_key(x):
max_val = max(x.values())
for key, value in x.items():
if value == max_val:
@@ -496,12 +494,12 @@ def max_key(x):
'c'
```
-The downside of this is that it iterates over `x` twice: once via `max` and once via the for-loop. The optimal solution for this only involves a single iteration, however it requires advanced concepts that are beyond the scope of the material presented here. We include the ideal solution for posterity:
+这个函数的不利之处在于它迭代了 `x` 两次;一次由 `max`,一次由for循环。这个问题的最优解仅仅迭代一次,但它用到了在超出本节纲领的进阶概念。我们在此为未来的你提供最优解:
-You can provide the `max` function with "key" argument, which accepts the function that should be used to evaluate the "value" for each iteration, which is used to discern the max element. Here, we pass it the built-in dictionary-function [get](https://docs.python.org/3/library/stdtypes.html#dict.get), which takes in a dictionary's key as an argument, and returns the corresponding value from the mapping. Thus `max` will iterate over each key of `x`, and discern the maximum value by comparing the value returned by each `x.get(key)` (which is effectively the same as `x[key]`).
+你可以为 `max` 函数提供“key”参数。这个参数接受用来计算每轮迭代的“值”的函数,而这个值就是 `max` 函数用来找出最大成员的使用的值。在此,我们向其输入内置的词典函数[get](https://docs.python.org/3/library/stdtypes.html#dict.get)。它接受词典的键为参数并返回对应的值。所以 `max` 会迭代 `x` 的每一个值并通过对比每个 `x.get(key)`(这和 `x[key]` 功能基本一样)来寻找最大值。
```python
-# optimal solution (for the sake of completeness)
+# 最优解(在此为完整性提供)
def max_key_optimal(x):
return max(x, key=x.get)
```
@@ -510,9 +508,9 @@ def max_key_optimal(x):
'd'
```
-You can read more about this `key` parameter [here](https://docs.python.org/3/howto/sorting.html#key-functions).
+你可以在[这里](https://docs.python.org/3/howto/sorting.html#key-functions)阅读 `key` 参数。
-Next, generalize your solution for a dictionary whose values are not necessarily unique. Return a tuple of the keys that map to that max value.
+接下来,让你的解可以处理词典有重复值的情况。返回成员为对应最大值的键的元组。
```python
def get_maxes(dictionary):
diff --git a/Python/Module2_EssentialsOfPython/ForLoops.md b/Python/Module2_EssentialsOfPython/ForLoops.md
index 4b37e61..52e5cfc 100644
--- a/Python/Module2_EssentialsOfPython/ForLoops.md
+++ b/Python/Module2_EssentialsOfPython/ForLoops.md
@@ -4,164 +4,164 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Contorl flow with for-loops and while-loops, Difficulty: Easy, Category: Section
:keywords: for-loop, while-loop, break, control flow, basic programming
-```
+
-# For-Loops and While-Loops
-In this section, we will introduce the essential "for-loop" control flow paradigm along with the formal definition of an "iterable". The utility of these items cannot be understated. Moving forward, you will likely find use for these concepts in nearly every piece of Python code that you write!
+# For循环和While循环
+在本节中我们将会介绍“for循环”控制流以及“可迭代物”(iterable)的正式定义。这些功能极其强大强大。在未来,你会在你编写的Python代码中随处见到这些概念!
-**Note**:
+**注**:
-There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.
+在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-## For-Loops
-A "for-loop" allows you to iterate over a collection of items, and execute a block of code once for each iteration. For example, the following code will sum up all the positive numbers in a tuple:
+## For循环
+一个“for循环”(for-loop)允许我们迭代某个集合中的成员,并为每一次成员执行同一块代码。比如说,以下的代码会求元组中所有正数的和:
```python
total = 0
for num in (-22.0, 3.5, 8.1, -10, 0.5):
if num > 0:
total = total + num
```
-The general syntax for a "for-loop" is:
+“for循环”的语法为:
```
for in :
- block of code
+ 一区块代码
```
-Where `` is any valid variable-identifier and `` is any **iterable**. We will discuss iterables more formally in the next section; suffice it to know that every sequence-type object is an iterable. The `for`statement must end in a colon character, and the body the for-loop is [whitespace-delimited](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope).
+`` 指代任何合法的变量身份(variable-identifier),`` 则是任何**可迭代物**。我们会在下一节中更正式地讨论迭代物;现在你只需要知道任何序列都是可迭代物这一事实就行了。`for` 语句必须由一个冒号结尾,且for循环的主体必须由[空格限定](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python使用空格来限定区域)。
-The for-loop behaves as follows:
+for循环的行为如下:
-- Request the next member of the iterable.
-- If the iterable is empty, exit the for-loop without running its body.
-- If the iterable did produce a member, assign that member to `` (if `` was not previously defined, it becomes defined).
-- Execute the enclosed body of code.
-- Go back to the first step.
+- 试图获取可迭代物的下一个成员。
+- 如果可迭代物是空的,退出for循环且不运行其主体代码。
+- 如果可迭代物提供了一个成员,为 `` 赋值为该成员(如果 `` 在之前并没有被定义,它将会在这里被定义)。
+- 执行循环的主体代码。
+- 返回第一步。
-To be concrete, let's consider the example:
+让我们来看一看一个例子吧:
```python
-# demonstrating a basic for-loop
+# 演示基本的for循环
total = 0
for item in [1, 3, 5]:
total = total + item
-print(total) # `total` has the value 1 + 3 + 5 = 9
-# `item` is still defined here, and holds the value 5
+print(total) # `total` 的值为 1 + 3 + 5 = 9
+# `item` 在这里依然被定义,且其值为5
```
-This code will perform the following steps:
+此代码会执行以下的步骤:
-1. Define the variable `total`, and assign it the value `0`
-2. Iterate on the list, producing value `1`, define the variable `item` and assign it the value `1`
-3. Assign `total` the value `0 + 1`
-4. Iterate on the list, producing the value `3` and assigning it to `item`
-5. Assign `total` the value `1 + 3`
-6. Iterate on the list, producing the value `5` and assigning it to `item`
-7. Assign `total` the value `4 + 5`
-8. Iterate on the list. Having reached its end, a `StopIteration` signal it raised by the list, and the for-loop sequence is exited.
-9. Print the value of `total` (9)
+1. 定义变量 `total`,并为其赋值 `0`
+2. 迭代此列表,得出值 `1`,定义变量 `item` 并为其赋值 `1`
+3. 为 `total` 赋值 `0 + 1`
+4. 迭代此列表,得出值 `3` 并为 `item` 赋值该数字
+5. 为 `total` 赋值 `1 + 3`
+6. 迭代此列表,得出值 `5` 并为 `item` 赋值该数字
+7. 为 `total` 赋值 `4 + 5`
+8. 迭代此列表。因为现在已经在列表结尾,列表将提供一个 `StopIteration` 信号,并导致for循环退出
+9. 打印 `total` 的值(9)
-#### Potential Pitfall
-Note that the variable `item` will persist after the for-loop block is exited. It will reference the last value from the for-loop iteration (in this case `item` has the value 5). That being said, *you should not write code that depends on the iterate-variable, outside of the context of the for-loop*. In the case that you try to loop over an *empty* iterable, the iterate-variable is never defined:
+#### 可能的错误
+注意迭代变量 `item` 在for循环退出之后依然存在。它会引用for循环迭代的最后一个值(在这个例子中 `item` 的值为5)。就算如此,*你不应该在for循环外面使用迭代变量*。因为如果你循环一个*空*的可迭代物,迭代变量不会被定义:
```python
-for x in []: # the iterable is empty - the iterate-variable `x` will not be defined
- print("Hello?") # this code is never executed
-print(x) # raises an error because `x` was never defined
+for x in []: # 可迭代物是空的——迭代变量 `x` 将不会被定义
+ print("Hello?") # 此代码不会被执行
+print(x) # 程序报错,因为 `x` 没有被定义
```
-Because we are attempting to iterate over an empty list, `StopIteration` is raised immediately - before the variable `x` is even defined. Thus the code enclosed within the for-loop is never reached, and the subsequent `print(x)` statement will raise a `NameError`, because `x` was never defined!
+当我们试图迭代一个空列表时,程序会在变量 `x` 被定义之前立刻收到 `StopIteration` 信号。for循环中的代码块一次都没有被执行。因为 `x` 没有被定义,之后的 `print(x)` 语句会导致 `NameError`!
-**Reading Comprehension: A basic for-loop**
+**阅读理解:简单for循环**
-Using a for-loop and an if-statement, print each letter in the string `"abcdefghij"`, if that letter is a vowel.
+使用一个for循环和一个if语句,打印字符串 `"abcdefghij"` 中的每一个元音(vowel,也就是aeiou这几个字母)。
-## While-Loops
-A "while-loop" allows you to repeat a block of code until a condition is no longer true:
+## While循环
+一个“while循环”(while-loop)允许你重复一区块代码,直到某个条件不再满足:
```
while :
- block of code
+ 代码块
```
-Where `` is an expression that returns `True` or `False`, or is any object on which `bool` can be called. The "body" of the while-loop is the code indented beneath the while-loop statement.
+`` 是一个会返回 `True` 或 `False` 的表达式,或任何可以转化为 `bool` 的对象。while循环的“主体”则是在循环语句下方缩进的代码。
-The while-loop behaves as follows:
+while循环的行为如下:
-- Call `bool()` and execute the indented block of code if `True` is returned. Otherwise, "exit" the while-loop, skipping past the indented code.
-- If the indented block code is executed, go back to the first step.
+- 执行 `bool()` 并在表达式返回 `True` 时执行下方缩进的代码区块。不然,“退出”while循环并跳过其缩进代码。
+- 如果缩进的代码块被执行了,回到第一步。
-To be concrete, let's consider the example:
+让我们观察一个例子:
```python
-# demonstrating a basic while-loop
+# 演示基本的while循环
total = 0
while total < 2:
- total += 1 # equivalent to: `total = total + 1`
+ total += 1 # 和 `total = total + 1` 等值
-print(total) # `total` has the value 2
+print(total) # `total` 现在的值为 2
```
-This code will perform the following steps:
+此代码会执行以下步骤:
-1. Define the variable `total`, and assign it the value `0`
-2. Evaluate `0 < 2`, which returns `True`: enter the enclosed code-block
-3. Execute the code block: assign `total` the value `0 + 1`
-4. Evaluate `1 < 2`, which returns `True`: enter the enclosed code-block
-5. Execute the code block: assign `total` the value `1 + 1`
-6. Evaluate `2 < 2`, which returns `False`: *skip* the enclosed code-block
-7. Print the value of `total` (2)
+1. 定义变量 `total`,并为其赋值 `0`
+2. 运算 `0 < 2`,其返回 `True`:进入循环主体的代码块
+3. 执行代码块:为 `total` 赋值 `0 + 1`
+4. 运算 `1 < 2`,其返回 `True`:进入循环主体的代码块
+5. 执行代码块:为 `total` 赋值 `1 + 1`
+6. 运算 `2 < 2`,其返回 `False`:*跳过*循环主体的代码块
+7. 打印 `total` 的值(2)
-Note that if we started off with `total = 3`, the condition-expression `3 < 2` would evaluate to `False` outright, and the indented body of code would never be reached.
+注意,如果我们一开始定义 `total = 3`,那条件表达式 `3 < 2` 会直接返回 `False`,且缩进的代码块将一次都不会执行。
-**Warning!**
+**警告!**
-It is possible to write a while-loop such that its conditional statement is always True, in which case your code will run ceaselessly! If this ever happens to you in a Jupyter notebook, either interrupt or restart your kernel.
+你可能(一不小心)编写了条件语句永远为真的while循环。这会导致你的代码无限运行!如果这在Jupyter记事本中意外发生,打断或重启你的壳(kernel)。
-**Reading Comprehension: A basic while-loop**
+**阅读理解:简单while循环**
-Given a list of nonzero, positive numbers, `x`, append the sum of that list to the end of it. Do this until the last value in `x` is at least 100. Use a while-loop.
+设一列表 `x`,其成员皆为的非零正数。在列表的结尾附加列表所有值的和。重复进行这一步,直到 `x` 的最后一个成员的值至少是100。使用一个while循环。
-If you start with `x = [1]`, then by the end of your while-loop `x` should be `[1, 1, 2, 4, 8, 16, 32, 64, 128]`.
+如果你定义 `x = [1]`,那在你的while循环结束后 `x` 应该是 `[1, 1, 2, 4, 8, 16, 32, 64, 128]`。
-## `break`, `continue`, & `else` clauses on loops
-The `continue` and `break` statements can be used within the bodies of both for-loops and while-loops. They provide added means for "short-circuiting" or prematurely exiting a given loop, respectively.
+## 循环中的 `break`,`continue`,和 `else` 句段
+你可以在for循环和while循环的主体中使用 `continue` 和 `break` 语句。它们分别提供一些额外的“短路”和提前退出循环的方式。
-Encountering `break` within a given loop causes that loop to be exited immediately:
+在循环中遇到 `break` 会导致程序立刻退出循环:
-```ipython
-# breaking out of a loop early
+```python
+# 提前退出循环
>>> for item in [1, 2, 3, 4, 5]:
... if item == 3:
... print(item, " ...break!")
@@ -174,10 +174,10 @@ Encountering `break` within a given loop causes that loop to be exited immediate
3 ...break!
```
-An `else` clause can be added to the end of any loop. The body of this else-statement will be executed *only if the loop was not exited via a `break` statement*.
+你可以在任何循环结尾添加一个 `else` 句段。此else语句的主体*只有在循环自然退出(没有被 `break` 语句打断)后才会执行*。
-```ipython
-# including an else-clause at the end of the loop
+```python
+# 在循环结尾添加一个else句段
>>> for item in [2, 4, 6]:
... if item == 3:
... print(item, " ...break!")
@@ -193,9 +193,9 @@ An `else` clause can be added to the end of any loop. The body of this else-stat
if you are reading this, then the loop completed without a 'break'
```
-The `continue` statement, when encountered within a loop, causes the loop-statement to be revisited immediately.
+在循环中遇到 `continue` 语句会导致程序立刻回到检查条件语句这一步。
```python
-# demonstrating a `continue` statement in a loop
+# 演示循环中的 `continue` 语句
>>> x = 1
>>> while x < 4:
... print("x = ", x, ">> enter loop-body <<")
@@ -218,25 +218,25 @@ x = 3 >> enter loop-body <<
-**Reading Comprehension: conducting flow in a loop**
+**阅读理解:控制循环中的流**
-Loop over a list of integers repeatedly, summing up all of its even values, and adding the content to a total. Repeat this process until the the total exceeds 100, or if you have looped over the list more than 50 times. Print the total only if it exceeds 100.
+重复循环一个整数列表,求其中偶数的和并将此和加到一个总值中。重复此过程,直到总值超过100,或已经循环这个列表超过50次。在总值大于等于100时打印它。
-## Links to Official Documentation
+## 官方说明文档链接
-- ['for' statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)
-- ['while' statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)
-- ['break', 'continue', and 'else' clauses](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
-- ['pass' statment](https://docs.python.org/3/tutorial/controlflow.html#pass-statements)
+- [“for”语句](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)
+- [“while”语句](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)
+- [“break”,“continue”,和“else”句段](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
+- [“pass”语句](https://docs.python.org/3/tutorial/controlflow.html#pass-statements)
-## Reading Comprehension Exercise Solutions:
+## 阅读理解答案
-**A basic for-loop: Solution**
+**简单for循环:解**
```python
for letter in "abcdefghij":
if letter in "aeiou":
@@ -246,7 +246,7 @@ for letter in "abcdefghij":
-**A basic while-loop: Solution**
+**简单while循环:解**
```python
while x[-1] < 100:
x.append(sum(x))
@@ -254,7 +254,7 @@ while x[-1] < 100:
-**Conducting flow in a loop: Solution**
+**控制循环中的流:解**
```python
x = [3, 4, 1, 2, 8, 10, -3, 0]
@@ -263,16 +263,16 @@ total = 0
while total < 100:
for item in x:
- # return to for-loop if
- # `item` is odd-valued
+ # 当 `item` 是奇数时立刻跳到
+ # 下一轮for循环
if item % 2 == 1:
continue
else:
total += item
num_loop += 1
-
- # break from while-loop if
- # more than 50 items tallied
+
+ # 只有在循环了50次之后才
+ # 打断while循环中
if 50 < num_loop:
break
else:
diff --git a/Python/Module2_EssentialsOfPython/Functions.md b/Python/Module2_EssentialsOfPython/Functions.md
index a2d8c6c..333b0a1 100644
--- a/Python/Module2_EssentialsOfPython/Functions.md
+++ b/Python/Module2_EssentialsOfPython/Functions.md
@@ -4,51 +4,51 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
- format_version: '1.1'
- jupytext_version: 1.1.0-rc0
+ format_version: '1.2'
+ jupytext_version: 1.3.0rc2
kernelspec:
display_name: Python 3
language: python
name: python3
---
-```raw_mimetype="text/restructuredtext"
+
.. meta::
:description: Topic: Functions and Function Signatures, Difficulty: Medium, Category: Section
:keywords: functions, *args, **kwargs, signature, default parameter, docstring, return, vowel count, syntax, basics
-```
+
-# Basics of Functions
+# 函数基础
-**Note**:
+**注**:
-There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.
+在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-Defining a function allows you to encapsulate a segment of code, specifying the information that enters and leaves the code. You can make use of this "code-capsule" repeatedly and in many different contexts. For example, suppose you want to count how many vowels are in a string. The following defines a function that accomplishes this:
+定义函数允许我们包装代码片段并描述进入和离开其中的信息。你可以在各种情况下重复使用这个“代码胶囊”。比如说,假设你想要数一个字符串中有多少元音,你可以定义以下的函数来达到该目的:
```python
def count_vowels(in_string):
- """ Returns the number of vowels contained in `in_string`"""
+ """ 返回 `in_string` 中有多少元音 """
num_vowels = 0
vowels = "aeiouAEIOU"
for char in in_string:
if char in vowels:
- num_vowels += 1 # equivalent to num_vowels = num_vowels + 1
+ num_vowels += 1 # 等值于 num_vowels = num_vowels + 1
return num_vowels
```
-Executing this code will define the *function* `count_vowels`. This function expects to be passed one object, represented by `in_string`, as an *input argument*, and it will *return* the number of vowels stored in that object. Invoking `count_vowels`, passing it an input object, is referred to as *calling* the function:
+执行此代码会定义*函数* `count_vowels`。这个函数期待一个对象作为*输入参数*(input argument),由 `in_string` 代名,并会*返回*(return)该对象中元音的数量。使用 `count_vowels` 并向其输入一个对象的过程叫做*调用*(call)该函数:
```python
>>> count_vowels("Hi my name is Ryan")
5
```
-The great thing about this is that it can be used over and over!
+最棒的一点在于你可以重复使用这个函数!
```python
>>> count_vowels("Apple")
@@ -58,62 +58,61 @@ The great thing about this is that it can be used over and over!
4
```
-In this section, we will learn about the syntax for defining and calling functions in Python
+在本节中,我们将会了解定义和调用Python函数的语法。
-**Definition**:
+**定义**:
-A Python **function** is an object that encapsulates code. *Calling* the function will execute the encapsulated code and *return* an object. A function can be defined so that it accepts *arguments*, which are objects that are to be passed to the encapsulated code.
+Python**函数**(function)是一个包装代码的对象。*调用*(call)函数将会执行包装的代码并*返回*(return)一个对象。你可以定义函数使其接受*参数*(argument),也就是输入进包装代码的对象。
-
-## The `def` Statement
-Similar to `if`, `else`, and `for`, the `def` statement is reserved by the Python language to signify the definition of functions (and a few other things that we'll cover later). The following is the general syntax for defining a Python function:
+
+## `def` 语句
+类似于 `if`,`else`,和 `for`,Python保留了 `def` 语句来表达函数(以及我们会在之后讨论的其它几个构造体)的定义。以下是Python函数定义的一般形式:
```
def ():
- """ documentation string """
+ """ 说明字符串 """
return