Skip to content

Commit 8139df3

Browse files
committed
feat: update chapter(s) by CAT
1 parent d7c90cb commit 8139df3

File tree

1 file changed

+74
-10
lines changed

1 file changed

+74
-10
lines changed

content/chapter-3/306.md

+74-10
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,46 @@
11
---
22
id:
3-
title: "[译] [XXX] XXXXXXXXXXXXXXXX"
3+
title: "[译] [306] 与 Copilot 配合创建优秀函数的示例"
44
---
55

6-
76
## 3.6 Examples of creating good functions with Copilot
7+
## 3.6 与 Copilot 配合创建优秀函数的示例
88

99
In this section, we’re going to write a bunch of functions with Copilot. We’ll be coding them entirely in Copilot to help you see the cycle of function design we just described. Although our goal in this chapter isn’t to help you read code just yet, we will be seeing programming features (sometimes called constructs) in the solutions that are very common in code (e.g., if statements, loops) so we’ll point those out when we see them. Then in Chapter 4, we’ll say more about how to read this code in more detail.
1010

11+
在本节中,我们将使用 Copilot 编写一系列函数。我们会全程利用 Copilot 进行编程,以便您能更好地理解我们先前提到的函数设计流程。尽管本章的目标并不是立刻教会您阅读代码,但我们还是会在解决方案中看到各种编程特性(有时也称作编程结构),这些特性在代码中非常常见(例如,if 语句、循环),因此我们会在看到它们时指出。然后在第四章,我们将更详细地讨论如何读懂这些代码。
12+
1113
Many of the functions we’re about to work on are unrelated to each other. For example, we’ll start with a function about stock share prices and move to functions about strong passwords. You typically wouldn’t store unrelated stuff like this in the same Python file. But as we’re just exploring different examples of good functions, please feel free to store all functions in the same Python file, perhaps named `function_practice.py` or `ch3.py`.
1214

15+
我们接下来要编写的函数,大多数是彼此不相关的。比如,我们会先编写一个关于股票价格的函数,接着是关于强密码的函数。通常,你不会把这些风马牛不相及的代码放在同一个 Python 文件里。不过,既然我们现在只是在探索如何编写好的函数的各种示例,那么就请随意把所有的函数都放在一个 Python 文件里,可以命名为 `function_practice.py` 或者 `ch3.py`
16+
1317
### 3.6.1 Dan’s stock pick
18+
### 3.6.1 阿丹的股票选择
1419

1520
Dan is an investor in a stock called AAAPL. He purchased 10 shares for $15 each. Now, each of those shares is worth $17. Dan would like to know how much money he has made on the stock.
1621

22+
阿丹投资了一支名为 AAAPL 的股票。他曾以每股15美元的价格购入了10股。如今,这些股票的每股价值已经上升到17美元。阿丹渴望了解他在这项投资中究竟获利多少。
23+
1724
Remember that we want to make our function as general as possible. If the only thing our function could do is calculate this exact AAAPL situation, it wouldn’t be that useful in general. Sure, it would help Dan right now, but what about when AAAPL’s share price changes again, or when he is interested in another stock entirely?
1825

26+
要记住,我们希望函数具有尽可能广泛的通用性。倘若我们的函数仅适用于计算 AAAPL 此刻的涨跌情况,那么它的实用性就大打折扣了。诚然,这在当下对阿丹有所帮助,但如果 AAAPL 的股价再次波动,或者他开始关注其他股票,那怎么办?
27+
1928
A useful general function here would take three parameters, all of which are numbers. The first parameter is the number of shares purchased, the second is the share price when the shares were purchased, and the third is the current share price. Let’s call this function `money_made`, since it’s going to determine how much money we’ve made or lost on the stock. In general, you want to name your function as an action word or words that describe what your function is doing. With that, we have enough to write the function header:
2029

30+
一个实用的通用函数应当接收三个参数,这三个参数均为数字类型。首个参数代表购买的股票数量,第二个参数代表购买时每股的股价,而第三个参数则是目前每股的股价。我们将这个函数命名为 `money_made`,因为它的作用是计算我们在股票投资上的盈亏。在命名函数时,通常会选用一个动词或短语来描述函数的功能。如此,我们就可以撰写函数的声明部分了:
31+
2132
```python
2233
def money_made(num_shares, purchase_share_price, current_share_price):
2334
```
2435

2536
Now we need a docstring. In the docstring, we need to explain what each parameter is for by using its name in a sentence. We also need to include what the function is supposed to do.
2637

38+
接下来,我们要撰写一个文档字符串。在这个文档字符串里,我们要通过一句话来阐明每个参数的作用,并在其中提及参数的名称。同时,我们也要指明这个函数旨在实现的功能。
39+
2740
Adding our docstring, here is the full prompt that we provide to Copilot:
2841

42+
加入我们的文档注释,这是我们给 Copilot 的完整提问:
43+
2944
```python
3045
def money_made(num_shares, purchase_share_price, current_share_price):
3146
"""
@@ -36,87 +51,136 @@ Return the amount of money we have earned on the stock.
3651
"""
3752
```
3853

54+
```python
55+
def money_made(num_shares, purchase_share_price, current_share_price):
56+
"""
57+
num_shares 是我们购买的股票数量。
58+
purchase_share_price 是每股的购买价格。
59+
current_share_price 是当前的股价。
60+
返回我们在股票上赚取的金额。
61+
"""
62+
```
3963

4064
After typing that prompt, go to the next line and press the tab key. Copilot will fill in the code for the function. Don’t worry that the code gets indented: the code of functions is supposed to be indented, and in fact it’s an error if it isn’t!
4165

66+
输入完那段提示词后,按下回车键,然后按Tab键继续。Copilot会自动填充函数的代码。请注意,代码的缩进是必要的,如果代码没有正确缩进,那将是一个错误!
67+
4268
Here’s what we got from Copilot:
4369

70+
这就是我们从Copilot那里获得的代码:
71+
4472
```python
45-
return num_shares * (current_share_price - purchase_share_price)
73+
return num_shares * (current_share_price - purchase_share_price)
4674
```
4775

48-
4976
This code seems sensible. In the parentheses it figures out the difference between the current price and the purchase price (the `-` is used for subtraction), and then it multiplies that by the number of shares that we have (the `*` is used for multiplication). Inspecting code like this is a useful skill, and we’ll get serious about it in the next chapter. Another useful skill is testing the function.
5077

78+
这段代码看起来合情合理。它利用括号计算出当前股价与购买时股价的差价(使用 `-` 表示减法),再将这个差价乘以我们所持有的股份数量(使用 `*` 表示乘法)。细致检查此类代码能够锻炼我们的编程能力,我们将在接下来的章节中深入探讨。同时,对函数进行测试也是一项重要的技能。
79+
5180
To test the function, we call it using various inputs and observe the output in each case. We could do this by asking Copilot to call the function and then running our program, much as we did with our “larger” function. We could then ask Copilot to change the function call by asking it to call the function with a different input, and run our program again, repeating as many times as needed.
5281

82+
要测试这个函数,我们可以采用不同的输入来调用它,并观察各个情况下的输出结果。我们可以请求Copilot来调用这个函数,接着执行我们的程序,正如我们之前对待那个“较为复杂”的函数一样。之后,我们可以请Copilot通过改变输入参数来重新调用函数,并再次执行程序,这样的测试可以根据需要反复进行。
83+
5384
However, we find it easier and more convenient to call the function ourselves from an interactive window.
5485

86+
不过,我们认为直接通过交互式窗口来调用函数更加轻松便捷。
87+
5588
This way, we can call the function as many times as we like without going through Copilot at all, and without cluttering up our program with stuff we’re going to delete anyway. To try this interactive approach, select/highlight all of the code of the function, then press `<Shift>+Enter` (you can access a similar interactive session by selecting the text, right-clicking, and choosing Run Selection/Line in Python Window, but the guidance here is if you use `<Shift>+Enter`). Figure 3.4 shows what this looks like if you select the text of the function and press `<Shift>+Enter`.
5689

57-
> Figure 3.4 Running Python in an interactive session in the Terminal of VSCode. Note the \>>> at the bottom of the Terminal.
90+
这样,我们就可以随意调用函数,完全不需要通过 Copilot,也避免了在我们的程序里填满最终要删除的冗余代码。要尝试这种交互方式,选中/高亮函数的所有代码,然后按下 `<Shift>+Enter`(此外,通过选中文本,右键并选择“在 Python 窗口中运行选择/行”也能进入这种的交互式会话,但此处建议使用 `<Shift>+Enter`)。图 3.4 展示了如果你选中函数文本并按下 `<Shift>+Enter` 会是什么样子。
91+
92+
> Figure 3.4 Running Python in an interactive session in the Terminal of VSCode. Note the `>>>` at the bottom of the Terminal.
5893
94+
> 图 3.4 在 VS Code 终端里运行 Python 交互式会话。请注意终端底部的 `>>>` 提示符。
5995
6096
![](https://raw.githubusercontent.com/cssmagic/Learn-AI-Assisted-Python-Programming/master/content/_figures/3.4.png)
6197

6298
At the bottom of the resulting window, you will see three greater-than symbols >>>. This is called a _prompt_, and you’re allowed to type Python code here. (This _prompt_ has nothing to do with the kind of prompt that we use when interacting with Copilot.) It will show us the result of the code that we type right away, which is convenient and fast.
6399

100+
在结果窗口底部,你会看到三个大于号 `>>>`。这个叫做 “提示符”,你可以直接在这里编写 Python 代码。(注意,这个提示符和我们与 Copilot 互动时所用的提示词是两码事。)它会立刻展示我们代码的执行结果,非常方便和迅速。
101+
64102
To call our `money_made` function, we need to provide three arguments, and they will be assigned left to right to the parameters. Whatever we put first will be assigned to `num_shares`, whatever we put second will be assigned to `purchase_share_price`, and whatever we put third will be assigned to `current_share_price`.
65103

104+
要调用我们的 `money_made` 函数,我们需要提供三个数值,它们将按照顺序分别赋值给函数的参数。我们最先给出的数值将赋值给 `num_shares`,第二个数值将赋值给 `purchase_share_price`,而第三个数值将赋值给 `current_share_price`
105+
66106
Let’s try this! At the prompt, type the following and press enter (or `<shift>+Enter`). Don’t type the >>> as that’s already there, and we are including it throughout the book to make it clear where we are typing. Please see figure 3.5 for an example of running the function in the terminal at the Python prompt.
67107

108+
来试试吧!在提示符处输入上述内容,然后按回车(或 `<shift>+Enter`)。无需输入`>>>`,它已经显示在那里了,我们全书都这样标注,以便清晰指示输入点。图 3.5 展示了在终端窗口的 Python 提示符下运行函数的实际效果。
109+
68110
```
69111
>>> money_made(10, 15, 17)
70112
```
71113

72114
You’ll see an output of
73115

116+
你将看到输出结果如下:
117+
74118
```
75119
20
76120
```
77121

78-
79122
Is `20` correct? Well, we bought 10 shares, and each of them went up $2 (from $15 to $17), so we did make $20. Looks good!
80123

81-
> Figure 3.5 Calling the `money_made` function from Python prompt in the VSCode Terminal.
124+
`20` 这个答案正确吗?嗯,我们买了 10 股,每股涨了 2 美元(从 15 美元涨到 17 美元),所以我们确实赚了 20 美元。看起来不错!
82125

83-
![](https://raw.githubusercontent.com/cssmagic/Learn-AI-Assisted-Python-Programming/master/content/_figures/3.5.png)
84126

127+
> Figure 3.5 Calling the `money_made` function from Python prompt in the VSCode Terminal.
85128
129+
> 图 3.5 在 VS Code 终端窗口的 Python 提示符下调用 `money_made` 函数。
130+
131+
![](https://raw.githubusercontent.com/cssmagic/Learn-AI-Assisted-Python-Programming/master/content/_figures/3.5.png)
86132

87133
We’re not done testing, though. When testing a function, you want to test it in various ways, not just once. All one test case tells you is that it happened to work with the particular input values that you provided. The more test cases we try, each testing the function in a different way, the more confident we are that our function is correct.
88134

135+
测试工作尚未结束。对函数进行测试时,应该采用多种方法,而不仅仅局限于一次。单一的测试用例仅能说明函数在你给出的特定输入值下有效。我们进行的测试用例越多样化,每种用例都从不同角度检验函数,我们对该函数正确性的把握就越大。
136+
89137
How do we test this function in a different way? We’re looking for inputs that are somehow a different _category_ of input. One not-so-good test right now would be to say, “what if our stock went from $15 to $18, instead of $15 to $17?”. This is pretty much the same test as before, and chances are that it will work just fine.
90138

139+
我们怎样才能用另一种方法来测试这个函数呢?我们需要寻找的输入,应该是另一种不同“类型”的数据。举个例子,我们把刚才股价从15美元涨到17美元的情况,换成15美元涨到18美元,这就不算是一个太好的测试。这样的测试和之前的太相似了,很可能函数同样能够很好地处理。
140+
91141
A good idea is to test what happens when the stock actually _loses money_. We expect to get a negative return value in this case. And it appears that our function works just fine with this category of test. Here’s our function call and the output that is returned to us:
92142

143+
测试一下股票实际发生**亏损**的情形是个不错的主意。我们预期在这种情况下会得到一个负收益。结果表明,我们的函数对这种类型的测试也能够很好地应对。以下是我们进行的函数调用及其返回结果:
144+
93145
```
94146
>>> money_made(10, 17, 15)
95147
-20
96148
```
97149

98150
What other tests can we do? Well, sometimes a stock price doesn’t change at all. We expect 0 in this case. Let’s verify it:
99151

152+
我们还能做些什么其他的测试吗?比如说,有时候股票的价格可能完全没有变化。在这种情况下,我们预期收益应该是0。让我们来验证这一点:
153+
100154
```
101155
>>> money_made(10, 15, 15)
102156
0
103157
```
104158

105159
Looks good!
106160

161+
看起来不错!
162+
107163
Testing is a combination of science and art. How many categories of things are there to test? Are these two calls really two different categories? Have we missed any categories? You will improve your testing ability through practice, and we’ll spend all of Chapter 6 talking about testing. For now, it looks like our `money_made` function is doing its job.
108164

165+
测试既是一门科学,也是一门艺术。我们究竟需要测试哪些种类的问题?这两个函数调用真的代表了两个截然不同的测试类别吗?我们是否遗漏了某些类别?通过不断的实践,你的测试技巧将得到提升,而在第六章中,我们将全面探讨有关测试的话题。就目前而言,我们的`money_made`函数似乎正在有效地履行其职责。
166+
109167
It’s possible for a function to use variables (rather than just its parameters) in its code, and we want to show you an example of that now so that you’re ready when you see Copilot doing it.
110168

169+
函数在其代码中可以使用变量(而不仅仅是其参数),我们现在就给你展示一个例子,以便将来遇到 Copilot 这样做时你能够应对自如。
170+
111171
Here’s an equivalent way to write the code for our `money_made` function:
112172

173+
这里展示了另一种编写 `money_made` 函数代码的等价方式:
174+
113175
```python
114-
price_difference = current_share_price - purchase_share_price
115-
return num_shares * price_difference
176+
price_difference = current_share_price - purchase_share_price
177+
return num_shares * price_difference
116178
```
117179

118180
This may even be easier to read for you: first it figures out the difference in share price, and then it multiplies that by the number of shares. We encourage you to test this version to help convince yourself that it is still correct.
119181

182+
这样的表达或许更加清晰:先计算出每股的差价,再将其与持股数量相乘。建议你同样对这个版本进行测试,以确保它也是正确的。
183+
120184
### 3.6.2 Leo’s password
121185

122186
Leo is signing up for a new social network website called ProgrammerBook. He wants to make sure that his password is strong.

0 commit comments

Comments
 (0)