Merge pull request #29 from Relph1119/master

修改代码行号的格式
This commit is contained in:
Datairon 2023-06-27 21:17:42 +08:00 committed by GitHub
commit 21f9d973d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 575 additions and 541 deletions

View File

@ -18,25 +18,25 @@
  这本书的目的是教会你作为编程新手所需的三种最重要的技能:读和写、注重细节、发现不同。   这本书的目的是教会你作为编程新手所需的三种最重要的技能:读和写、注重细节、发现不同。
一、读和写 **一、读和写**
  如果你连打字都不行,那你学习编程也会成问题。尤其如果你连程序源代码中的那些奇怪字符都打不出来,就别提编程了。没有这些基本技能,你将连最基本的软件工作原理都难以学会。   如果你连打字都不行,那你学习编程也会成问题。尤其如果你连程序源代码中的那些奇怪字符都打不出来,就别提编程了。没有这些基本技能,你将连最基本的软件工作原理都难以学会。
  所以,把代码示例打出来并运行,能够帮助你学习各种符号的名称、更熟练地敲出来、以及读懂编程语言。   所以,把代码示例打出来并运行,能够帮助你学习各种符号的名称、更熟练地敲出来、以及读懂编程语言。
二、注意细节 **二、注意细节**
  区分好程序员和差程序员的一个重要标准,就是对细节的注重程度。事实上,这也是任何行业区分好坏的标准。如果缺乏对工作中每个微小细节的注意,你的工作成果将缺乏重要的元素。拿编程来讲,主要细节将会让你远离各种 Bug 和难用的系统。   区分好程序员和差程序员的一个重要标准,就是对细节的注重程度。事实上,这也是任何行业区分好坏的标准。如果缺乏对工作中每个微小细节的注意,你的工作成果将缺乏重要的元素。拿编程来讲,主要细节将会让你远离各种 Bug 和难用的系统。
  通过这本书的学习,以及准确打出每一个例子,你将能够训练你的大脑,在做练习的时候更多地关注细节。   通过这本书的学习,以及准确打出每一个例子,你将能够训练你的大脑,在做练习的时候更多地关注细节。
三、发现不同 **三、发现不同**
  程序员长年累月的工作会培养出一个重要技能,那就是对于不同点的区分能力。一个有经验的程序员看到两个仅有细微差别的程序,可以立即指出其中的不同。程序员还造出工具来让这件事更加容易,不过我们不会用到这些工具。你要先用笨办法训练自己,然后再用工具。   程序员长年累月的工作会培养出一个重要技能,那就是对于不同点的区分能力。一个有经验的程序员看到两个仅有细微差别的程序,可以立即指出其中的不同。程序员还造出工具来让这件事更加容易,不过我们不会用到这些工具。你要先用笨办法训练自己,然后再用工具。
  在你做这些练习并敲代码的时候你一定会出错。这是不可避免的即使有经验的程序员也会偶尔写错。你的任务是把自己写的东西和要求的正确答案对比把所有的不同点都修正过来。这样做可以让你对程序里的错误、Bug 以及其他问题更加敏感。   在你做这些练习并敲代码的时候你一定会出错。这是不可避免的即使有经验的程序员也会偶尔写错。你的任务是把自己写的东西和要求的正确答案对比把所有的不同点都修正过来。这样做可以让你对程序里的错误、Bug 以及其他问题更加敏感。
四、要问,不要盯着看 **四、要问,不要盯着看**
  你只要写代码,就会出现 Bug。Bug 意味着你写的代码有瑕疵、有错误、或者有问题。Bug 来源于一个传说从前有一只飞蛾飞进了第一台计算机造成了故障。修复它就需要“debugging”。在软件世界里有着不计其数的 Bug。   你只要写代码,就会出现 Bug。Bug 意味着你写的代码有瑕疵、有错误、或者有问题。Bug 来源于一个传说从前有一只飞蛾飞进了第一台计算机造成了故障。修复它就需要“debugging”。在软件世界里有着不计其数的 Bug。
@ -44,11 +44,11 @@
  怎么寻找呢?你需要审问你的代码,问它现在是怎么回事儿,或者从另一个不同的视角去看待这个问题。在这本书里,我将会频繁地告诉你“别盯着看,要问”。我将会向你演示如何让你的代码告诉你正在发生的一切,并且如何找到可能的解决方案。我还会教你一些从不同角度看代码的方法,让你能够获取更多信息和洞见。   怎么寻找呢?你需要审问你的代码,问它现在是怎么回事儿,或者从另一个不同的视角去看待这个问题。在这本书里,我将会频繁地告诉你“别盯着看,要问”。我将会向你演示如何让你的代码告诉你正在发生的一切,并且如何找到可能的解决方案。我还会教你一些从不同角度看代码的方法,让你能够获取更多信息和洞见。
五、不要复制粘贴 **五、不要复制粘贴**
  你必须手动将每个练习打出来。复制粘贴会让这些练习变得毫无意义。这些习题的目的是训练你的双手和大脑思维,让你有能力读代码、写代码、观察代码。如果你复制粘贴,那你就是在欺骗自己,这些练习的效果也将大打折扣。   你必须手动将每个练习打出来。复制粘贴会让这些练习变得毫无意义。这些习题的目的是训练你的双手和大脑思维,让你有能力读代码、写代码、观察代码。如果你复制粘贴,那你就是在欺骗自己,这些练习的效果也将大打折扣。
六、一个关于坚持练习的忠告 **六、一个关于坚持练习的忠告**
  在你通过这本书学习编程时,我正在学习弹吉他。我每天至少练习 2 个小时,至少花一个小时练习音阶、和声、和弦,剩下的时间用来学习音乐理论和歌曲演奏以及训练听力等。有时我一天会花 8 个小时来练习,因为我觉得这是一件有趣的事情。对我来说,重复性练习是学好一样东西最自然而然的方法。并且我深知,要掌握一件事情,只有每天坚持练习。虽然有时候,我整个人状态很差(甚至经常这样),或者觉得实在太难。没关系,坚持尝试,到最后你会发现它越来越简单,并且开始越来越有趣。   在你通过这本书学习编程时,我正在学习弹吉他。我每天至少练习 2 个小时,至少花一个小时练习音阶、和声、和弦,剩下的时间用来学习音乐理论和歌曲演奏以及训练听力等。有时我一天会花 8 个小时来练习,因为我觉得这是一件有趣的事情。对我来说,重复性练习是学好一样东西最自然而然的方法。并且我深知,要掌握一件事情,只有每天坚持练习。虽然有时候,我整个人状态很差(甚至经常这样),或者觉得实在太难。没关系,坚持尝试,到最后你会发现它越来越简单,并且开始越来越有趣。

View File

@ -11,15 +11,17 @@ print('hallo world')
  认识注释,注释是由 # 加上相关备注,但是不会在代码中运行,可以作为帮助理解的功能。   认识注释,注释是由 # 加上相关备注,但是不会在代码中运行,可以作为帮助理解的功能。
```python ```{code-block} python
1 # A comment, this is so you can read your program later. :linenos:
2 # Anything after the # is ignored by python.
3 # A comment, this is so you can read your program later.
4 print("I could have code like this.") # and the comment after 5 # Anything after the # is ignored by python.
6 # You can also use a comment to "disable" or comment out code
7 # print("This won't run.") print("I could have code like this.") # and the comment after 5
8 # You can also use a comment to "disable" or comment out code
9 print("This will run.") # print("This won't run.")
print("This will run.")
``` ```
## 2.2 数学运算 ## 2.2 数学运算
@ -37,30 +39,32 @@ print('hallo world')
- `>=` greater-than-equal大于等于号 - `>=` greater-than-equal大于等于号
```python ```{code-block} python
1 print("I will now count my chickens:") :linenos:
2
3 print("Hens", 25 + 30 / 6) print("I will now count my chickens:")
4 print("Roosters", 100 - 25 * 3 % 4)
5 print("Hens", 25 + 30 / 6)
6 print("Now I will count the eggs:") print("Roosters", 100 - 25 * 3 % 4)
7
8 print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("Now I will count the eggs:")
9
10 print("Is it true that 3 + 2 < 5 - 7?") print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
11
12 print(3 + 2 < 5 - 7) print("Is it true that 3 + 2 < 5 - 7?")
13
14 print("What is 3 + 2?", 3 + 2) print(3 + 2 < 5 - 7)
15 print("What is 5 - 7?", 5 - 7)
16 print("What is 3 + 2?", 3 + 2)
17 print("Oh, that's why it's False.") print("What is 5 - 7?", 5 - 7)
18
19 print("How about some more.") print("Oh, that's why it's False.")
20
21 print("Is it greater?", 5 > -2) print("How about some more.")
22 print("Is it greater or equal?", 5 >= -2)
23 print("Is it less or equal?", 5 <= -2) print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
``` ```
&emsp;&emsp;将上述代码输入到Python的运行环境中并执行该代码你应该会看到的结果是 &emsp;&emsp;将上述代码输入到Python的运行环境中并执行该代码你应该会看到的结果是
@ -97,47 +101,50 @@ Is it less or equal? False
### 2.3.1 字符是如何引用的 ### 2.3.1 字符是如何引用的
```python ```{code-block} python
1 cars = 100 :linenos:
2 space_in_a_car = 4.0
3 drivers = 30 cars = 100
4 passengers = 90 space_in_a_car = 4.0
5 cars_not_driven = cars - drivers drivers = 30
6 cars_driven = drivers passengers = 90
7 carpool_capacity = cars_driven * space_in_a_car cars_not_driven = cars - drivers
8 average_passengers_per_car = passengers / cars_driven cars_driven = drivers
9 carpool_capacity = cars_driven * space_in_a_car
10 average_passengers_per_car = passengers / cars_driven
11 print("There are", cars, "cars available.")
12 print("There are only", drivers, "drivers available.") print("There are", cars, "cars available.")
13 print("There will be", cars_not_driven, "empty cars today.") print("There are only", drivers, "drivers available.")
14 print("We can transport", carpool_capacity, "people today.") print("There will be", cars_not_driven, "empty cars today.")
15 print("We have", passengers, "to carpool today.") print("We can transport", carpool_capacity, "people today.")
16 print("We need to put about", average_passengers_per_car, print("We have", passengers, "to carpool today.")
17 "in each car.") print("We need to put about", average_passengers_per_car,
"in each car.")
``` ```
&emsp;&emsp;下面我们来打印一下个人的信息: &emsp;&emsp;下面我们来打印一下个人的信息:
```python ```{code-block} python
1 my_name = 'Zed A. Shaw' :linenos:
2 my_age = 35 # not a lie
3 my_height = 74 # inches my_name = 'Zed A. Shaw'
4 my_weight = 180 # lbs my_age = 35 # not a lie
5 my_eyes = 'Blue' my_height = 74 # inches
6 my_teeth = 'White' my_weight = 180 # lbs
7 my_hair = 'Brown' my_eyes = 'Blue'
8 my_teeth = 'White'
9 print(f"Let's talk about {my_name}.") my_hair = 'Brown'
10 print(f"He's {my_height} inches tall.")
11 print(f"He's {my_weight} pounds heavy.") print(f"Let's talk about {my_name}.")
12 print("Actually that's not too heavy.") print(f"He's {my_height} inches tall.")
13 print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"He's {my_weight} pounds heavy.")
14 print(f"His teeth are usually {my_teeth} depending on the coffee.") print("Actually that's not too heavy.")
15 print(f"He's got {my_eyes} eyes and {my_hair} hair.")
16 # this line is tricky, try to get it exactly right print(f"His teeth are usually {my_teeth} depending on the coffee.")
17 total = my_age + my_height + my_weight
18 print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") # this line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
``` ```
#### 练习1 #### 练习1
@ -147,29 +154,31 @@ Is it less or equal? False
### 2.3.2 输入一整段字符串、变量和格式 ### 2.3.2 输入一整段字符串、变量和格式
&emsp;&emsp;程序员都喜欢使用简短的缩写来节省时间,但是那些缩写在你看来会十分晦涩难懂。所以我们得尽早开始学习阅读和书写这些东西。 &emsp;&emsp;程序员都喜欢使用简短的缩写来节省时间,但是那些缩写在你看来会十分晦涩难懂。所以我们得尽早开始学习阅读和书写这些东西。
```python ```{code-block} python
1 types_of_people = 10 :linenos:
2 x = f"There are {types_of_people} types of people."
3 types_of_people = 10
4 binary = "binary" x = f"There are {types_of_people} types of people."
5 do_not = "don't"
6 y = f"Those who know {binary} and those who {do_not}." binary = "binary"
7 do_not = "don't"
8 print(x) y = f"Those who know {binary} and those who {do_not}."
9 print(y)
10 print(x)
11 print(f"I said: {x}") print(y)
12 print(f"I also said: '{y}'")
13 print(f"I said: {x}")
14 hilarious = False print(f"I also said: '{y}'")
15 joke_evaluation = "Isn't that joke so funny?! {}"
16 hilarious = False
17 print(joke_evaluation.format(hilarious)) joke_evaluation = "Isn't that joke so funny?! {}"
18
19 w = "This is the left side of..." print(joke_evaluation.format(hilarious))
20 e = "a string with a right side."
21 w = "This is the left side of..."
22 print(w + e) e = "a string with a right side."
print(w + e)
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:

View File

@ -60,68 +60,70 @@ Neato
&emsp;&emsp;注意一下这个例子是如何把美国的州名和它们的缩写以及州的缩写和城市映射mapping起来的记住“映射”或者说“关联”associate是字典的核心理念。 &emsp;&emsp;注意一下这个例子是如何把美国的州名和它们的缩写以及州的缩写和城市映射mapping起来的记住“映射”或者说“关联”associate是字典的核心理念。
```python ```{code-block} python
1 # create a mapping of state to abbreviation :linenos:
2 states = {
3 'Oregon': 'OR', # create a mapping of state to abbreviation
4 'Florida': 'FL', states = {
5 'California': 'CA', 'Oregon': 'OR',
6 'New York': 'NY', 'Florida': 'FL',
7 'Michigan': 'MI' 'California': 'CA',
8 } 'New York': 'NY',
9 'Michigan': 'MI'
10 # create a basic set of states and some cities in them }
11 cities = {
12 'CA': 'San Francisco', # create a basic set of states and some cities in them
13 'MI': 'Detroit', cities = {
14 'FL': 'Jacksonville' 'CA': 'San Francisco',
15 } 'MI': 'Detroit',
16 'FL': 'Jacksonville'
17 # add some more cities }
18 cities['NY'] = 'New York'
19 cities['OR'] = 'Portland' # add some more cities
20 cities['NY'] = 'New York'
21 # print out some cities cities['OR'] = 'Portland'
22 print('-' * 10)
23 print("NY State has: ", cities['NY']) # print out some cities
24 print("OR State has: ", cities['OR']) print('-' * 10)
25 print("NY State has: ", cities['NY'])
26 # print some states print("OR State has: ", cities['OR'])
27 print('-' * 10)
28 print("Michigan's abbreviation is: ", states['Michigan']) # print some states
29 print("Florida's abbreviation is: ", states['Florida']) print('-' * 10)
30 print("Michigan's abbreviation is: ", states['Michigan'])
31 # do it by using the state then cities dict print("Florida's abbreviation is: ", states['Florida'])
32 print('-' * 10)
33 print("Michigan has: ", cities[states['Michigan']]) # do it by using the state then cities dict
34 print("Florida has: ", cities[states['Florida']]) print('-' * 10)
35 print("Michigan has: ", cities[states['Michigan']])
36 # print every state abbreviation print("Florida has: ", cities[states['Florida']])
37 print('-' * 10)
38 for state, abbrev in list(states.items()): # print every state abbreviation
39 print(f"{state} is abbreviated {abbrev}") print('-' * 10)
40 for state, abbrev in list(states.items()):
41 # print every city in state print(f"{state} is abbreviated {abbrev}")
42 print('-' * 10)
43 for abbrev, city in list(cities.items()): # print every city in state
44 print(f"{abbrev} has the city {city}") print('-' * 10)
45 for abbrev, city in list(cities.items()):
46 # now do both at the same time print(f"{abbrev} has the city {city}")
47 print('-' * 10)
48 for state, abbrev in list(states.items()): # now do both at the same time
49 print(f"{state} state is abbreviated {abbrev}") print('-' * 10)
50 print(f"and has city {cities[abbrev]}") for state, abbrev in list(states.items()):
51 print(f"{state} state is abbreviated {abbrev}")
52 print('-' * 10) print(f"and has city {cities[abbrev]}")
53 # safely get a abbreviation by state that might not be there
54 state = states.get('Texas') print('-' * 10)
55 # safely get a abbreviation by state that might not be there
56 if not state: state = states.get('Texas')
57 print("Sorry, no Texas.")
58 if not state:
59 # get a city with a default value print("Sorry, no Texas.")
60 city = cities.get('TX', 'Does Not Exist')
61 print(f"The city for the state 'TX' is: {city}") # get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")
``` ```
### 练习1 ### 练习1
@ -169,27 +171,29 @@ list[2] = 1000 # 列表中是合法应用
&emsp;&emsp;在这个练习中,你将试着在 Python 中运用逻辑表示。给以下每一个逻辑问题写下你认为的答案,要么是 True要么是 False。等你把答案写下来再在终端里运行 Python输入每个逻辑问题来确认你的答案是否正确。 &emsp;&emsp;在这个练习中,你将试着在 Python 中运用逻辑表示。给以下每一个逻辑问题写下你认为的答案,要么是 True要么是 False。等你把答案写下来再在终端里运行 Python输入每个逻辑问题来确认你的答案是否正确。
```python ```{code-block} python
1 True and True :linenos:
2 False and True
3 1 == 1 and 2 == 1 True and True
4 "test" == "test" False and True
5 1 == 1 or 2 != 1 1 == 1 and 2 == 1
6 True and 1 == 1 "test" == "test"
7 False and 0 != 0 1 == 1 or 2 != 1
8 True or 1 == 1 True and 1 == 1
9 "test" == "testing" False and 0 != 0
10 1 != 0 and 2 == 1 True or 1 == 1
11 "test" != "testing" "test" == "testing"
12 "test" == 1 1 != 0 and 2 == 1
13 not (True and False) "test" != "testing"
14 not (1 == 1 and 0 != 1) "test" == 1
15 not (10 == 1 or 1000 == 1000) not (True and False)
16 not (1 != 10 or 3 == 4) not (1 == 1 and 0 != 1)
17 not ("testing" == "testing" and "Zed" == "Cool Guy") not (10 == 1 or 1000 == 1000)
18 1 == 1 and (not ("testing" == 1 or 1 == 0)) not (1 != 10 or 3 == 4)
19 "chunky" == "bacon" and (not (3 == 4 or 3 == 3)) not ("testing" == "testing" and "Zed" == "Cool Guy")
20 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) 1 == 1 and (not ("testing" == 1 or 1 == 0))
"chunky" == "bacon" and (not (3 == 4 or 3 == 3))
3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))
``` ```
&emsp;&emsp;在你尝试给出所有答案后,这是你可能会在 Python 运行后看到的运行结果: &emsp;&emsp;在你尝试给出所有答案后,这是你可能会在 Python 运行后看到的运行结果:

View File

@ -12,29 +12,30 @@
&emsp;&emsp;你可以通过在 Python 中使用`def`来创建一个函数。我会让你创建 4 个不同的函数,它们就像你的脚本一样运行,之后我还会展示每一个之间是如何关联的。 &emsp;&emsp;你可以通过在 Python 中使用`def`来创建一个函数。我会让你创建 4 个不同的函数,它们就像你的脚本一样运行,之后我还会展示每一个之间是如何关联的。
```python ```{code-block} python
1 # this one is like your scripts with argv :linenos:
2 def print_two(*args): # this one is like your scripts with argv
3 arg1, arg2 = args def print_two(*args):
4 print(f"arg1: {arg1}, arg2: {arg2}") arg1, arg2 = args
5 print(f"arg1: {arg1}, arg2: {arg2}")
6 # ok, that *args is actually pointless, we can just do this
7 def print_two_again(arg1, arg2): # ok, that *args is actually pointless, we can just do this
8 print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2):
9 print(f"arg1: {arg1}, arg2: {arg2}")
10 # this just takes one argument
11 def print_one(arg1): # this just takes one argument
12 print(f"arg1: {arg1}") def print_one(arg1):
13 print(f"arg1: {arg1}")
14 # this one takes no arguments
15 def print_none(): # this one takes no arguments
16 print("I got nothin'.") def print_none():
17 print("I got nothin'.")
18
19 print_two("Zed","Shaw")
20 print_two_again("Zed","Shaw") print_two("Zed","Shaw")
21 print_one("First!") print_two_again("Zed","Shaw")
22 print_none() print_one("First!")
print_none()
``` ```
&emsp;&emsp;让我们把第一个函数拆解一下,`print_two` 这是你从创建脚本中已经学到的最熟悉的东西: &emsp;&emsp;让我们把第一个函数拆解一下,`print_two` 这是你从创建脚本中已经学到的最熟悉的东西:
@ -128,31 +129,32 @@ Tips
&emsp;&emsp;有个小点你可能没注意到,我们会在之后进行强化:你函数里面的变量跟你脚本里面的变量没有关联。通过下面这个练习思考一下这个问题: &emsp;&emsp;有个小点你可能没注意到,我们会在之后进行强化:你函数里面的变量跟你脚本里面的变量没有关联。通过下面这个练习思考一下这个问题:
```python ```{code-block} python
1 def cheese_and_crackers(cheese_count, boxes_of_crackers): :linenos:
2 print(f"You have {cheese_count} cheeses!")
3 print(f"You have {boxes_of_crackers} boxes of crackers!" def cheese_and_crackers(cheese_count, boxes_of_crackers):
4 print("Man that's enough for a party!") print(f"You have {cheese_count} cheeses!")
5 print("Get a blanket.\n") print(f"You have {boxes_of_crackers} boxes of crackers!"
6 print("Man that's enough for a party!")
7 print("Get a blanket.\n")
8 print("We can just give the function numbers directly:")
9 cheese_and_crackers(20, 30)
10 print("We can just give the function numbers directly:")
11 cheese_and_crackers(20, 30)
12 print("OR, we can use variables from our script:")
13 amount_of_cheese = 10
14 amount_of_crackers = 50 print("OR, we can use variables from our script:")
15 amount_of_cheese = 10
16 cheese_and_crackers(amount_of_cheese, amount_of_crackers) amount_of_crackers = 50
17
18 cheese_and_crackers(amount_of_cheese, amount_of_crackers)
19 print("We can even do math inside too:")
20 cheese_and_crackers(10 + 20, 5 + 6)
21 print("We can even do math inside too:")
22 cheese_and_crackers(10 + 20, 5 + 6)
23 print("And we can combine the two, variables and math:")
24 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
``` ```
&emsp;&emsp;这个练习展示了我们可以给函数`cheese_and_crackers`赋值的几种不同的方式,可以直接给它数字,或者变量,亦或是数学运算,甚至是数学运算和变量的结合。 &emsp;&emsp;这个练习展示了我们可以给函数`cheese_and_crackers`赋值的几种不同的方式,可以直接给它数字,或者变量,亦或是数学运算,甚至是数学运算和变量的结合。
@ -163,7 +165,9 @@ Tips
&emsp;&emsp;你应该研究一下这个脚本的输出结果,把它和你之前的脚本输出结果对比一下。 &emsp;&emsp;你应该研究一下这个脚本的输出结果,把它和你之前的脚本输出结果对比一下。
```python ```{code-block} python
:linenos:
We can just give the function numbers directly: We can just give the function numbers directly:
You have 20 cheeses! You have 20 cheeses!
You have 30 boxes of crackers! You have 30 boxes of crackers!
@ -223,40 +227,42 @@ Get a blanket.
&emsp;&emsp;记住你的函数`checklist`,然后在做这个练习的时候注意函数是如何和文件一起工作并发挥一些作用的。 &emsp;&emsp;记住你的函数`checklist`,然后在做这个练习的时候注意函数是如何和文件一起工作并发挥一些作用的。
```python ```{code-block} python
1 from sys import argv :linenos:
2
3 script, input_file = argv from sys import argv
4
5 def print_all(f): script, input_file = argv
6 print(f.read())
7 def print_all(f):
8 def rewind(f): print(f.read())
9 f.seek(0)
10 def rewind(f):
11 def print_a_line(line_count, f): f.seek(0)
12 print(line_count, f.readline())
13 def print_a_line(line_count, f):
14 current_file = open(input_file) print(line_count, f.readline())
15
16 print("First let's print the whole file:\n") current_file = open(input_file)
17
18 print_all(current_file) print("First let's print the whole file:\n")
19
20 print("Now let's rewind, kind of like a tape.") print_all(current_file)
21
22 rewind(current_file) print("Now let's rewind, kind of like a tape.")
23
24 print("Let's print three lines:") rewind(current_file)
25
26 current_line = 1 print("Let's print three lines:")
27 print_a_line(current_line, current_file)
28 current_line = 1
29 current_line = current_line + 1 print_a_line(current_line, current_file)
30 print_a_line(current_line, current_file)
31 current_line = current_line + 1
32 current_line = current_line + 1 print_a_line(current_line, current_file)
33 print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
``` ```
&emsp;&emsp;着重注意我们是如何在每次运行`print_a_line`的时候把当前行的数字传递出去的。 &emsp;&emsp;着重注意我们是如何在每次运行`print_a_line`的时候把当前行的数字传递出去的。
@ -317,40 +323,42 @@ Let's print three lines:
&emsp;&emsp;你已经使用了`=`来命名变量,并给变量赋予数值或字符串。接下来我会教你如何用`=`和一个新的 Python 字符`return`来把函数中的变量设置为一个值。有一点需要密切注意,但是先输入如下代码: &emsp;&emsp;你已经使用了`=`来命名变量,并给变量赋予数值或字符串。接下来我会教你如何用`=`和一个新的 Python 字符`return`来把函数中的变量设置为一个值。有一点需要密切注意,但是先输入如下代码:
```python ```{code-block} python
1 def add(a, b): :linenos:
2 print(f"ADDING {a} + {b}")
3 return a + b def add(a, b):
4 print(f"ADDING {a} + {b}")
5 def subtract(a, b): return a + b
6 print(f"SUBTRACTING {a} - {b}")
7 return a - b def subtract(a, b):
8 print(f"SUBTRACTING {a} - {b}")
9 def multiply(a, b): return a - b
10 print(f"MULTIPLYING {a} * {b}")
11 return a * b def multiply(a, b):
12 print(f"MULTIPLYING {a} * {b}")
13 def divide(a, b): return a * b
14 print(f"DIVIDING {a} / {b}")
15 return a / b def divide(a, b):
16 print(f"DIVIDING {a} / {b}")
17 return a / b
18 print("Let's do some math with just functions!")
19
20 age = add(30, 5) print("Let's do some math with just functions!")
21 height = subtract(78, 4)
22 weight = multiply(90, 2) age = add(30, 5)
23 iq = divide(100, 2) height = subtract(78, 4)
24 weight = multiply(90, 2)
25 print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") iq = divide(100, 2)
26
27 print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")
28 # A puzzle for the extra credit, type it in anyway.
29 print("Here is a puzzle.")
30 # A puzzle for the extra credit, type it in anyway.
31 what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print("Here is a puzzle.")
32
33 print("That becomes: ", what, "Can you do it by hand?") what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
``` ```
&emsp;&emsp;我们现在要做我们自己的加减乘除数学运算了。我说的要密切注意的是`add`函数里面的`return a + b`,这步做的是这些事情: &emsp;&emsp;我们现在要做我们自己的加减乘除数学运算了。我说的要密切注意的是`add`函数里面的`return a + b`,这步做的是这些事情:

View File

@ -1,4 +1,4 @@
# 3编程习惯养成与思维 # 3 编程习惯养成与思维
## 3.1 防御性编程与备注 ## 3.1 防御性编程与备注
@ -26,7 +26,7 @@ while i<x:
1. 选择一个可以计数的变量Choose variable that "count" 1. 选择一个可以计数的变量Choose variable that "count"
2. 在程序外部初始化它Initiative outside the loop 2. 在程序外部初始化它Initiative outside the loop
3. 需要设置正确的最终测试Setup and test 3. 需要设置正确的最终测试Setup and test
4. 构建代码块Conctract block 4. 构建代码块Contract block
5. 当结束并完成后,该如何去做 What to do when done 5. 当结束并完成后,该如何去做 What to do when done
### 代码效率 ### 代码效率

View File

@ -4,36 +4,38 @@
#### 4.1.1 IF语句的使用 #### 4.1.1 IF语句的使用
```python ```{code-block} python
1 people = 20 :linenos:
2 cats = 30
3 dogs = 15 people = 20
4 cats = 30
5 dogs = 15
6 if people < cats:
7 print("Too many cats! The world is doomed!")
8 if people < cats:
9 if people > cats: print("Too many cats! The world is doomed!")
10 print("Not many cats! The world is saved!")
11 if people > cats:
12 if people < dogs: print("Not many cats! The world is saved!")
13 print("The world is drooled on!")
14 if people < dogs:
15 if people > dogs: print("The world is drooled on!")
16 print("The world is dry!")
17 if people > dogs:
18 print("The world is dry!")
19 dogs += 5
20
21 if people >= dogs: dogs += 5
22 print("People are greater than or equal to dogs.")
23 if people >= dogs:
24 if people <= dogs: print("People are greater than or equal to dogs.")
25 print("People are less than or equal to dogs.")
26 if people <= dogs:
27 print("People are less than or equal to dogs.")
28 if people == dogs:
29 print("People are dogs.")
if people == dogs:
print("People are dogs.")
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:
@ -100,30 +102,32 @@ People are dogs.
&emsp;&emsp;把我的答案和你的比较一下,然后确保你真的理解了代码块的概念。这对你进行接下来的练习很重要。把下面的代码输入进去然后运行。 &emsp;&emsp;把我的答案和你的比较一下,然后确保你真的理解了代码块的概念。这对你进行接下来的练习很重要。把下面的代码输入进去然后运行。
```python ```{code-block} python
1 people = 30 :linenos:
2 cars = 40
3 trucks = 15 people = 30
4 cars = 40
5 trucks = 15
6 if cars > people:
7 print("We should take the cars.")
8 elif cars < people: if cars > people:
9 print("We should not take the cars.") print("We should take the cars.")
10 else: elif cars < people:
11 print("We can't decide.") print("We should not take the cars.")
12 else:
13 if trucks > cars: print("We can't decide.")
14 print("That's too many trucks.")
15 elif trucks < cars: if trucks > cars:
16 print("Maybe we could take the trucks.") print("That's too many trucks.")
17 else: elif trucks < cars:
18 print("We still can't decide.") print("Maybe we could take the trucks.")
19 else:
20 if people > trucks: print("We still can't decide.")
21 print("Alright, let's just take the trucks.")
22 else: if people > trucks:
23 print("Fine, let's stay home then.") print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:
@ -162,45 +166,47 @@ Alright, let's just take the trucks.
&emsp;&emsp;在上个脚本中,你写出了一个简单的问问题的测试集。在这个练习中,你将问用户一些问题,并基于他们的回答做决定。写下这个脚本,然后多玩几遍,把它弄明白。 &emsp;&emsp;在上个脚本中,你写出了一个简单的问问题的测试集。在这个练习中,你将问用户一些问题,并基于他们的回答做决定。写下这个脚本,然后多玩几遍,把它弄明白。
```python ```{code-block} python
1 print("""You enter a dark room with two doors. :linenos:
2 Do you go through door #1 or door #2?""")
3 print("""You enter a dark room with two doors.
4 door = input("> ") Do you go through door #1 or door #2?""")
5
6 if door == "1": door = input("> ")
7 print("There's a giant bear here eating a cheese cake.")
8 print("What do you do?") if door == "1":
9 print("1. Take the cake.") print("There's a giant bear here eating a cheese cake.")
10 print("2. Scream at the bear.") print("What do you do?")
11 print("1. Take the cake.")
12 bear = input("> ") print("2. Scream at the bear.")
13
14 if bear == "1": bear = input("> ")
15 print("The bear eats your face off. Good job!")
16 elif bear == "2": if bear == "1":
17 print("The bear eats your legs off. Good job!") print("The bear eats your face off. Good job!")
18 else: elif bear == "2":
19 print(f"Well, doing {bear} is probably better.") print("The bear eats your legs off. Good job!")
20 print("Bear runs away.") else:
21 print(f"Well, doing {bear} is probably better.")
22 elif door == "2": print("Bear runs away.")
23 print("You stare into the endless abyss at Cthulhu's retina.")
24 print("1. Blueberries.") elif door == "2":
25 print("2. Yellow jacket clothespins.") print("You stare into the endless abyss at Cthulhu's retina.")
26 print("3. Understanding revolvers yelling melodies.") print("1. Blueberries.")
27 print("2. Yellow jacket clothespins.")
28 insanity = input("> ") print("3. Understanding revolvers yelling melodies.")
29
30 if insanity == "1" or insanity == "2": insanity = input("> ")
31 print("Your body survives powered by a mind of jello.")
32 print("Good job!") if insanity == "1" or insanity == "2":
33 else: print("Your body survives powered by a mind of jello.")
34 print("The insanity rots your eyes into a pool of muck.") print("Good job!")
35 print("Good job!") else:
36 print("The insanity rots your eyes into a pool of muck.")
37 else: print("Good job!")
38 print("You stumble around and fall on a knife and die. Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
``` ```
&emsp;&emsp;这里很关键的一点是在`if`语句里面又放了一个`if`语句。这在创建“嵌套”nested的时候非常有用每一个分支指向另一个选择。 &emsp;&emsp;这里很关键的一点是在`if`语句里面又放了一个`if`语句。这在创建“嵌套”nested的时候非常有用每一个分支指向另一个选择。
@ -237,36 +243,38 @@ The bear eats your legs off. Good job!
### 4.2 FOR语句 ### 4.2 FOR语句
```python ```{code-block} python
1 the_count = [1, 2, 3, 4, 5] :linenos:
2 fruits = ['apples', 'oranges', 'pears', 'apricots']
3 change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] the_count = [1, 2, 3, 4, 5]
4 fruits = ['apples', 'oranges', 'pears', 'apricots']
5 # this first kind of for-loop goes through a list change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
6 for number in the_count:
7 print(f"This is count {number}") # this first kind of for-loop goes through a list
8 for number in the_count:
9 # same as above print(f"This is count {number}")
10 for fruit in fruits:
11 print(f"A fruit of type: {fruit}") # same as above
12 for fruit in fruits:
13 # also we can go through mixed lists too print(f"A fruit of type: {fruit}")
14 # notice we have to use {} since we don't know what's in it
15 for i in change: # also we can go through mixed lists too
16 print(f"I got {i}") # notice we have to use {} since we don't know what's in it
17 for i in change:
18 # we can also build lists, first start with an empty one print(f"I got {i}")
19 elements = []
20 # we can also build lists, first start with an empty one
21 # then use the range function to do 0 to 5 counts elements = []
22 for i in range(0, 6):
23 print(f"Adding {i} to the list.") # then use the range function to do 0 to 5 counts
24 # append is a function that lists understand for i in range(0, 6):
25 elements.append(i) print(f"Adding {i} to the list.")
26 # append is a function that lists understand
27 # now we can print them out too elements.append(i)
28 for i in elements:
29 print(f"Element was: {i}") # now we can print them out too
for i in elements:
print(f"Element was: {i}")
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:
@ -346,23 +354,25 @@ Element was: 5
&emsp;&emsp;在这个练习中,你要通过以下三个检查来学习`while-loop` &emsp;&emsp;在这个练习中,你要通过以下三个检查来学习`while-loop`
```python ```{code-block} python
1 i = 0 :linenos:
2 numbers = []
3 i = 0
4 while i < 6: numbers = []
5 print(f"At the top i is {i}")
6 numbers.append(i) while i < 6:
7 print(f"At the top i is {i}")
8 i = i + 1 numbers.append(i)
9 print("Numbers now: ", numbers)
10 print(f"At the bottom i is {i}") i = i + 1
11 print("Numbers now: ", numbers)
12 print(f"At the bottom i is {i}")
13 print("The numbers: ")
14
15 for num in numbers: print("The numbers: ")
16 print(num)
for num in numbers:
print(num)
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:
@ -429,84 +439,86 @@ The numbers:
&emsp;&emsp;目前为止你已经了解了`if`语句,函数以及列表。现在是时候深入学习一下了。照例输入如下代码,看看你能否明白程序在做什么。 &emsp;&emsp;目前为止你已经了解了`if`语句,函数以及列表。现在是时候深入学习一下了。照例输入如下代码,看看你能否明白程序在做什么。
```python ```{code-block} python
1 from sys import exit :linenos:
2
3 def gold_room(): from sys import exit
4 print("This room is full of gold. How much do you take?")
5 def gold_room():
6 choice = input("> ") print("This room is full of gold. How much do you take?")
7 if "0" in choice or "1" in choice:
8 how_much = int(choice) choice = input("> ")
9 else: if "0" in choice or "1" in choice:
10 dead("Man, learn to type a number.") how_much = int(choice)
11 else:
12 if how_much < 50: dead("Man, learn to type a number.")
13 print("Nice, you're not greedy, you win!")
14 exit(0) if how_much < 50:
15 else: print("Nice, you're not greedy, you win!")
16 dead("You greedy bastard!") exit(0)
17 else:
18 dead("You greedy bastard!")
19 def bear_room():
20 print("There is a bear here.")
21 print("The bear has a bunch of honey.") def bear_room():
22 print("The fat bear is in front of another door.") print("There is a bear here.")
23 print("How are you going to move the bear?") print("The bear has a bunch of honey.")
24 bear_moved = False print("The fat bear is in front of another door.")
25 print("How are you going to move the bear?")
26 while True: bear_moved = False
27 choice = input("> ")
28 while True:
29 if choice == "take honey": choice = input("> ")
30 dead("The bear looks at you then slaps your face")
31 elif choice == "taunt bear" and not bear_moved: if choice == "take honey":
32 print("The bear has moved from the door.") dead("The bear looks at you then slaps your face")
33 print("You can go through it now.") elif choice == "taunt bear" and not bear_moved:
34 bear_moved = True print("The bear has moved from the door.")
35 elif choice == "taunt bear" and bear_moved: print("You can go through it now.")
36 dead("The bear gets pissed off and chews your leg.") bear_moved = True
37 elif choice == "open door" and bear_moved: elif choice == "taunt bear" and bear_moved:
38 gold_room() dead("The bear gets pissed off and chews your leg.")
39 else: elif choice == "open door" and bear_moved:
40 print("I got no idea what that means.") gold_room()
41 else:
42 print("I got no idea what that means.")
43 def cthulhu_room():
44 print("Here you see the great evil Cthulhu.")
45 print("He, it, whatever stares at you and you go insane.") def cthulhu_room():
46 print("Do you flee for your life or eat your head?") print("Here you see the great evil Cthulhu.")
47 print("He, it, whatever stares at you and you go insane.")
48 choice = input("> ") print("Do you flee for your life or eat your head?")
49
50 if "flee" in choice: choice = input("> ")
51 start()
52 elif "head" in choice: if "flee" in choice:
53 dead("Well that was tasty!") start()
54 else: elif "head" in choice:
55 cthulhu_room() dead("Well that was tasty!")
56 else:
57 cthulhu_room()
58 def dead(why):
59 print(why, "Good job!")
60 exit(0) def dead(why):
61 print(why, "Good job!")
62 def start(): exit(0)
63 print("You are in a dark room.")
64 print("There is a door to your right and left.") def start():
65 print("Which one do you take?") print("You are in a dark room.")
66 print("There is a door to your right and left.")
67 choice = input("> ") print("Which one do you take?")
68
69 if choice == "left": choice = input("> ")
70 bear_room()
71 elif choice == "right": if choice == "left":
72 cthulhu_room() bear_room()
73 else: elif choice == "right":
74 dead("You stumble around the room until you starve.") cthulhu_room()
75 else:
76 dead("You stumble around the room until you starve.")
77 start()
start()
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果:

View File

@ -4,28 +4,29 @@
### 5.1 类的例子 ### 5.1 类的例子
```python ```{code-block} python
1 class Song(object): #class表示要创建类Song是类的名称 :linenos:
2
3 def __init__(self, lyrics): #称为构造方法,根据类创建对象时自动执行 class Song(object): #class表示要创建类Song是类的名称
4 self.lyrics = lyrics
#根据类 Song 创建对象 #根据类 Song 创建对象
#自动执行Song类的 __init__方法 #自动执行Song类的 __init__方法
5 def __init__(self, lyrics): #称为构造方法,根据类创建对象时自动执行
6 def sing_me_a_song(self): #定义sing_me_a_song函数 self.lyrics = lyrics
7 for line in self.lyrics: #采用for循环获取每一句歌词
8 print(line) #打印出来 def sing_me_a_song(self): #定义sing_me_a_song函数
9 for line in self.lyrics: #采用for循环获取每一句歌词
10 happy_bday = Song(["Happy birthday to you", print(line) #打印出来
11 "I don't want to get sued",
12 "So I'll stop right there"]) happy_bday = Song(["Happy birthday to you",
13 "I don't want to get sued",
14 bulls_on_parade = Song(["They rally around tha family", "So I'll stop right there"])
15 "With pockets full of shells"])
16 bulls_on_parade = Song(["They rally around tha family",
17 happy_bday.sing_me_a_song() "With pockets full of shells"])
18
19 bulls_on_parade.sing_me_a_song() happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
``` ```
&emsp;&emsp;上述代码的运行结果: &emsp;&emsp;上述代码的运行结果: