From dc746d866d7fed7d5cf8aba374e213075e8dc4c2 Mon Sep 17 00:00:00 2001 From: Relph1119 Date: Tue, 27 Jun 2023 11:28:29 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81=E8=A1=8C?= =?UTF-8?q?=E5=8F=B7=E7=9A=84=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../task2-数学运算、字符串和文本、列表.md | 195 ++++---- .../task3-字典、元组、布尔类型、读写文件.md | 170 +++---- PythonThinking/task4-函数.md | 242 +++++----- PythonThinking/task6-FOR、IF以及while.md | 448 +++++++++--------- PythonThinking/task7-面向对象的编程.md | 45 +- 5 files changed, 567 insertions(+), 533 deletions(-) diff --git a/PythonThinking/task2-数学运算、字符串和文本、列表.md b/PythonThinking/task2-数学运算、字符串和文本、列表.md index 1e19fca..a0f826d 100644 --- a/PythonThinking/task2-数学运算、字符串和文本、列表.md +++ b/PythonThinking/task2-数学运算、字符串和文本、列表.md @@ -11,15 +11,17 @@ print('hallo world')   认识注释,注释是由 # 加上相关备注,但是不会在代码中运行,可以作为帮助理解的功能。 -```python -1 # A comment, this is so you can read your program later. -2 # Anything after the # is ignored by python. -3 -4 print("I could have code like this.") # and the comment after 5 -6 # You can also use a comment to "disable" or comment out code -7 # print("This won't run.") -8 -9 print("This will run.") +```{code-block} python +:linenos: + +# A comment, this is so you can read your program later. +# Anything after the # is ignored by python. + +print("I could have code like this.") # and the comment after 5 +# You can also use a comment to "disable" or comment out code +# print("This won't run.") + +print("This will run.") ``` ## 2.2 数学运算 @@ -37,30 +39,32 @@ print('hallo world') - `>=` greater-than-equal,大于等于号 -```python -1 print("I will now count my chickens:") -2 -3 print("Hens", 25 + 30 / 6) -4 print("Roosters", 100 - 25 * 3 % 4) -5 -6 print("Now I will count the eggs:") -7 -8 print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) -9 -10 print("Is it true that 3 + 2 < 5 - 7?") -11 -12 print(3 + 2 < 5 - 7) -13 -14 print("What is 3 + 2?", 3 + 2) -15 print("What is 5 - 7?", 5 - 7) -16 -17 print("Oh, that's why it's False.") -18 -19 print("How about some more.") -20 -21 print("Is it greater?", 5 > -2) -22 print("Is it greater or equal?", 5 >= -2) -23 print("Is it less or equal?", 5 <= -2) +```{code-block} python +:linenos: + +print("I will now count my chickens:") + +print("Hens", 25 + 30 / 6) +print("Roosters", 100 - 25 * 3 % 4) + +print("Now I will count the eggs:") + +print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) + +print("Is it true that 3 + 2 < 5 - 7?") + +print(3 + 2 < 5 - 7) + +print("What is 3 + 2?", 3 + 2) +print("What is 5 - 7?", 5 - 7) + +print("Oh, that's why it's False.") + +print("How about some more.") + +print("Is it greater?", 5 > -2) +print("Is it greater or equal?", 5 >= -2) +print("Is it less or equal?", 5 <= -2) ```   将上述代码输入到Python的运行环境中,并执行该代码,你应该会看到的结果是: @@ -97,47 +101,50 @@ Is it less or equal? False ### 2.3.1 字符是如何引用的 -```python -1 cars = 100 -2 space_in_a_car = 4.0 -3 drivers = 30 -4 passengers = 90 -5 cars_not_driven = cars - drivers -6 cars_driven = drivers -7 carpool_capacity = cars_driven * space_in_a_car -8 average_passengers_per_car = passengers / cars_driven -9 -10 -11 print("There are", cars, "cars available.") -12 print("There are only", drivers, "drivers available.") -13 print("There will be", cars_not_driven, "empty cars today.") -14 print("We can transport", carpool_capacity, "people today.") -15 print("We have", passengers, "to carpool today.") -16 print("We need to put about", average_passengers_per_car, -17 "in each car.") +```{code-block} python +:linenos: + +cars = 100 +space_in_a_car = 4.0 +drivers = 30 +passengers = 90 +cars_not_driven = cars - drivers +cars_driven = drivers +carpool_capacity = cars_driven * space_in_a_car +average_passengers_per_car = passengers / cars_driven + +print("There are", cars, "cars available.") +print("There are only", drivers, "drivers available.") +print("There will be", cars_not_driven, "empty cars today.") +print("We can transport", carpool_capacity, "people today.") +print("We have", passengers, "to carpool today.") +print("We need to put about", average_passengers_per_car, + "in each car.") ```   下面我们来打印一下个人的信息: -```python -1 my_name = 'Zed A. Shaw' -2 my_age = 35 # not a lie -3 my_height = 74 # inches -4 my_weight = 180 # lbs -5 my_eyes = 'Blue' -6 my_teeth = 'White' -7 my_hair = 'Brown' -8 -9 print(f"Let's talk about {my_name}.") -10 print(f"He's {my_height} inches tall.") -11 print(f"He's {my_weight} pounds heavy.") -12 print("Actually that's not too heavy.") -13 print(f"He's got {my_eyes} eyes and {my_hair} hair.") -14 print(f"His teeth are usually {my_teeth} depending on the coffee.") -15 -16 # this line is tricky, try to get it exactly right -17 total = my_age + my_height + my_weight -18 print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") +```{code-block} python +:linenos: + +my_name = 'Zed A. Shaw' +my_age = 35 # not a lie +my_height = 74 # inches +my_weight = 180 # lbs +my_eyes = 'Blue' +my_teeth = 'White' +my_hair = 'Brown' + +print(f"Let's talk about {my_name}.") +print(f"He's {my_height} inches tall.") +print(f"He's {my_weight} pounds heavy.") +print("Actually that's not too heavy.") +print(f"He's got {my_eyes} eyes and {my_hair} hair.") +print(f"His teeth are usually {my_teeth} depending on the coffee.") + +# 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 @@ -147,29 +154,31 @@ Is it less or equal? False ### 2.3.2 输入一整段字符串、变量和格式   程序员都喜欢使用简短的缩写来节省时间,但是那些缩写在你看来会十分晦涩难懂。所以我们得尽早开始学习阅读和书写这些东西。 -```python -1 types_of_people = 10 -2 x = f"There are {types_of_people} types of people." -3 -4 binary = "binary" -5 do_not = "don't" -6 y = f"Those who know {binary} and those who {do_not}." -7 -8 print(x) -9 print(y) -10 -11 print(f"I said: {x}") -12 print(f"I also said: '{y}'") -13 -14 hilarious = False -15 joke_evaluation = "Isn't that joke so funny?! {}" -16 -17 print(joke_evaluation.format(hilarious)) -18 -19 w = "This is the left side of..." -20 e = "a string with a right side." -21 -22 print(w + e) +```{code-block} python +:linenos: + +types_of_people = 10 +x = f"There are {types_of_people} types of people." + +binary = "binary" +do_not = "don't" +y = f"Those who know {binary} and those who {do_not}." + +print(x) +print(y) + +print(f"I said: {x}") +print(f"I also said: '{y}'") + +hilarious = False +joke_evaluation = "Isn't that joke so funny?! {}" + +print(joke_evaluation.format(hilarious)) + +w = "This is the left side of..." +e = "a string with a right side." + +print(w + e) ```   上述代码的运行结果: diff --git a/PythonThinking/task3-字典、元组、布尔类型、读写文件.md b/PythonThinking/task3-字典、元组、布尔类型、读写文件.md index 5e33c68..4ebe6d5 100644 --- a/PythonThinking/task3-字典、元组、布尔类型、读写文件.md +++ b/PythonThinking/task3-字典、元组、布尔类型、读写文件.md @@ -60,68 +60,70 @@ Neato   注意一下这个例子是如何把美国的州名和它们的缩写以及州的缩写和城市映射(mapping)起来的,记住,“映射”或者说“关联”(associate)是字典的核心理念。 -```python -1 # create a mapping of state to abbreviation -2 states = { -3 'Oregon': 'OR', -4 'Florida': 'FL', -5 'California': 'CA', -6 'New York': 'NY', -7 'Michigan': 'MI' -8 } -9 -10 # create a basic set of states and some cities in them -11 cities = { -12 'CA': 'San Francisco', -13 'MI': 'Detroit', -14 'FL': 'Jacksonville' -15 } -16 -17 # add some more cities -18 cities['NY'] = 'New York' -19 cities['OR'] = 'Portland' -20 -21 # print out some cities -22 print('-' * 10) -23 print("NY State has: ", cities['NY']) -24 print("OR State has: ", cities['OR']) -25 -26 # print some states -27 print('-' * 10) -28 print("Michigan's abbreviation is: ", states['Michigan']) -29 print("Florida's abbreviation is: ", states['Florida']) -30 -31 # do it by using the state then cities dict -32 print('-' * 10) -33 print("Michigan has: ", cities[states['Michigan']]) -34 print("Florida has: ", cities[states['Florida']]) -35 -36 # print every state abbreviation -37 print('-' * 10) -38 for state, abbrev in list(states.items()): -39 print(f"{state} is abbreviated {abbrev}") -40 -41 # print every city in state -42 print('-' * 10) -43 for abbrev, city in list(cities.items()): -44 print(f"{abbrev} has the city {city}") -45 -46 # now do both at the same time -47 print('-' * 10) -48 for state, abbrev in list(states.items()): -49 print(f"{state} state is abbreviated {abbrev}") -50 print(f"and has city {cities[abbrev]}") -51 -52 print('-' * 10) -53 # safely get a abbreviation by state that might not be there -54 state = states.get('Texas') -55 -56 if not state: -57 print("Sorry, no Texas.") -58 -59 # get a city with a default value -60 city = cities.get('TX', 'Does Not Exist') -61 print(f"The city for the state 'TX' is: {city}") +```{code-block} python +:linenos: + +# create a mapping of state to abbreviation +states = { + 'Oregon': 'OR', + 'Florida': 'FL', + 'California': 'CA', + 'New York': 'NY', + 'Michigan': 'MI' +} + +# create a basic set of states and some cities in them +cities = { + 'CA': 'San Francisco', + 'MI': 'Detroit', + 'FL': 'Jacksonville' +} + +# add some more cities +cities['NY'] = 'New York' +cities['OR'] = 'Portland' + +# print out some cities +print('-' * 10) +print("NY State has: ", cities['NY']) +print("OR State has: ", cities['OR']) + +# print some states +print('-' * 10) +print("Michigan's abbreviation is: ", states['Michigan']) +print("Florida's abbreviation is: ", states['Florida']) + +# do it by using the state then cities dict +print('-' * 10) +print("Michigan has: ", cities[states['Michigan']]) +print("Florida has: ", cities[states['Florida']]) + +# print every state abbreviation +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} is abbreviated {abbrev}") + +# print every city in state +print('-' * 10) +for abbrev, city in list(cities.items()): + print(f"{abbrev} has the city {city}") + +# now do both at the same time +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} state is abbreviated {abbrev}") + print(f"and has city {cities[abbrev]}") + +print('-' * 10) +# safely get a abbreviation by state that might not be there +state = states.get('Texas') + +if not state: + print("Sorry, no Texas.") + +# 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 @@ -169,27 +171,29 @@ list[2] = 1000 # 列表中是合法应用   在这个练习中,你将试着在 Python 中运用逻辑表示。给以下每一个逻辑问题写下你认为的答案,要么是 True,要么是 False。等你把答案写下来,再在终端里运行 Python,输入每个逻辑问题,来确认你的答案是否正确。 -```python -1 True and True -2 False and True -3 1 == 1 and 2 == 1 -4 "test" == "test" -5 1 == 1 or 2 != 1 -6 True and 1 == 1 -7 False and 0 != 0 -8 True or 1 == 1 -9 "test" == "testing" -10 1 != 0 and 2 == 1 -11 "test" != "testing" -12 "test" == 1 -13 not (True and False) -14 not (1 == 1 and 0 != 1) -15 not (10 == 1 or 1000 == 1000) -16 not (1 != 10 or 3 == 4) -17 not ("testing" == "testing" and "Zed" == "Cool Guy") -18 1 == 1 and (not ("testing" == 1 or 1 == 0)) -19 "chunky" == "bacon" and (not (3 == 4 or 3 == 3)) -20 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) +```{code-block} python +:linenos: + +True and True +False and True +1 == 1 and 2 == 1 +"test" == "test" +1 == 1 or 2 != 1 +True and 1 == 1 +False and 0 != 0 +True or 1 == 1 +"test" == "testing" +1 != 0 and 2 == 1 +"test" != "testing" +"test" == 1 +not (True and False) +not (1 == 1 and 0 != 1) +not (10 == 1 or 1000 == 1000) +not (1 != 10 or 3 == 4) +not ("testing" == "testing" and "Zed" == "Cool Guy") +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")) ```   在你尝试给出所有答案后,这是你可能会在 Python 运行后看到的运行结果: diff --git a/PythonThinking/task4-函数.md b/PythonThinking/task4-函数.md index f9c072e..ea7d737 100644 --- a/PythonThinking/task4-函数.md +++ b/PythonThinking/task4-函数.md @@ -12,29 +12,30 @@   你可以通过在 Python 中使用`def`来创建一个函数。我会让你创建 4 个不同的函数,它们就像你的脚本一样运行,之后我还会展示每一个之间是如何关联的。 -```python -1 # this one is like your scripts with argv -2 def print_two(*args): -3 arg1, arg2 = args -4 print(f"arg1: {arg1}, arg2: {arg2}") -5 -6 # ok, that *args is actually pointless, we can just do this -7 def print_two_again(arg1, arg2): -8 print(f"arg1: {arg1}, arg2: {arg2}") -9 -10 # this just takes one argument -11 def print_one(arg1): -12 print(f"arg1: {arg1}") -13 -14 # this one takes no arguments -15 def print_none(): -16 print("I got nothin'.") -17 -18 -19 print_two("Zed","Shaw") -20 print_two_again("Zed","Shaw") -21 print_one("First!") -22 print_none() +```{code-block} python +:linenos: +# this one is like your scripts with argv +def print_two(*args): + arg1, arg2 = args + print(f"arg1: {arg1}, arg2: {arg2}") + +# ok, that *args is actually pointless, we can just do this +def print_two_again(arg1, arg2): + print(f"arg1: {arg1}, arg2: {arg2}") + +# this just takes one argument +def print_one(arg1): + print(f"arg1: {arg1}") + +# this one takes no arguments +def print_none(): + print("I got nothin'.") + + +print_two("Zed","Shaw") +print_two_again("Zed","Shaw") +print_one("First!") +print_none() ```   让我们把第一个函数拆解一下,`print_two` 这是你从创建脚本中已经学到的最熟悉的东西: @@ -128,31 +129,32 @@ Tips:   有个小点你可能没注意到,我们会在之后进行强化:你函数里面的变量跟你脚本里面的变量没有关联。通过下面这个练习思考一下这个问题: -```python -1 def cheese_and_crackers(cheese_count, boxes_of_crackers): -2 print(f"You have {cheese_count} cheeses!") -3 print(f"You have {boxes_of_crackers} boxes of crackers!" -4 print("Man that's enough for a party!") -5 print("Get a blanket.\n") -6 -7 -8 print("We can just give the function numbers directly:") -9 cheese_and_crackers(20, 30) -10 -11 -12 print("OR, we can use variables from our script:") -13 amount_of_cheese = 10 -14 amount_of_crackers = 50 -15 -16 cheese_and_crackers(amount_of_cheese, amount_of_crackers) -17 -18 -19 print("We can even do math inside too:") -20 cheese_and_crackers(10 + 20, 5 + 6) -21 -22 -23 print("And we can combine the two, variables and math:") -24 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) +```{code-block} python +:linenos: + +def cheese_and_crackers(cheese_count, boxes_of_crackers): + print(f"You have {cheese_count} cheeses!") + print(f"You have {boxes_of_crackers} boxes of crackers!" + print("Man that's enough for a party!") + print("Get a blanket.\n") + + +print("We can just give the function numbers directly:") +cheese_and_crackers(20, 30) + + +print("OR, we can use variables from our script:") +amount_of_cheese = 10 +amount_of_crackers = 50 + +cheese_and_crackers(amount_of_cheese, amount_of_crackers) + + +print("We can even do math inside too:") +cheese_and_crackers(10 + 20, 5 + 6) + +print("And we can combine the two, variables and math:") +cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) ```   这个练习展示了我们可以给函数`cheese_and_crackers`赋值的几种不同的方式,可以直接给它数字,或者变量,亦或是数学运算,甚至是数学运算和变量的结合。 @@ -163,7 +165,9 @@ Tips:   你应该研究一下这个脚本的输出结果,把它和你之前的脚本输出结果对比一下。 -```python +```{code-block} python +:linenos: + We can just give the function numbers directly: You have 20 cheeses! You have 30 boxes of crackers! @@ -223,40 +227,42 @@ Get a blanket.   记住你的函数`checklist`,然后在做这个练习的时候注意函数是如何和文件一起工作并发挥一些作用的。 -```python -1 from sys import argv -2 -3 script, input_file = argv -4 -5 def print_all(f): -6 print(f.read()) -7 -8 def rewind(f): -9 f.seek(0) -10 -11 def print_a_line(line_count, f): -12 print(line_count, f.readline()) -13 -14 current_file = open(input_file) -15 -16 print("First let's print the whole file:\n") -17 -18 print_all(current_file) -19 -20 print("Now let's rewind, kind of like a tape.") -21 -22 rewind(current_file) -23 -24 print("Let's print three lines:") -25 -26 current_line = 1 -27 print_a_line(current_line, current_file) -28 -29 current_line = current_line + 1 -30 print_a_line(current_line, current_file) -31 -32 current_line = current_line + 1 -33 print_a_line(current_line, current_file) +```{code-block} python +:linenos: + +from sys import argv + +script, input_file = argv + +def print_all(f): + print(f.read()) + +def rewind(f): + f.seek(0) + +def print_a_line(line_count, f): + print(line_count, f.readline()) + +current_file = open(input_file) + +print("First let's print the whole file:\n") + +print_all(current_file) + +print("Now let's rewind, kind of like a tape.") + +rewind(current_file) + +print("Let's print three lines:") + +current_line = 1 +print_a_line(current_line, current_file) + +current_line = current_line + 1 +print_a_line(current_line, current_file) + +current_line = current_line + 1 +print_a_line(current_line, current_file) ```   着重注意我们是如何在每次运行`print_a_line`的时候把当前行的数字传递出去的。 @@ -317,40 +323,42 @@ Let's print three lines:   你已经使用了`=`来命名变量,并给变量赋予数值或字符串。接下来我会教你如何用`=`和一个新的 Python 字符`return`来把函数中的变量设置为一个值。有一点需要密切注意,但是先输入如下代码: -```python -1 def add(a, b): -2 print(f"ADDING {a} + {b}") -3 return a + b -4 -5 def subtract(a, b): -6 print(f"SUBTRACTING {a} - {b}") -7 return a - b -8 -9 def multiply(a, b): -10 print(f"MULTIPLYING {a} * {b}") -11 return a * b -12 -13 def divide(a, b): -14 print(f"DIVIDING {a} / {b}") -15 return a / b -16 -17 -18 print("Let's do some math with just functions!") -19 -20 age = add(30, 5) -21 height = subtract(78, 4) -22 weight = multiply(90, 2) -23 iq = divide(100, 2) -24 -25 print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") -26 -27 -28 # A puzzle for the extra credit, type it in anyway. -29 print("Here is a puzzle.") -30 -31 what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) -32 -33 print("That becomes: ", what, "Can you do it by hand?") +```{code-block} python +:linenos: + +def add(a, b): + print(f"ADDING {a} + {b}") + return a + b + +def subtract(a, b): + print(f"SUBTRACTING {a} - {b}") + return a - b + +def multiply(a, b): + print(f"MULTIPLYING {a} * {b}") + return a * b + +def divide(a, b): + print(f"DIVIDING {a} / {b}") + return a / b + + +print("Let's do some math with just functions!") + +age = add(30, 5) +height = subtract(78, 4) +weight = multiply(90, 2) +iq = divide(100, 2) + +print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") + + +# A puzzle for the extra credit, type it in anyway. +print("Here is a puzzle.") + +what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) + +print("That becomes: ", what, "Can you do it by hand?") ```   我们现在要做我们自己的加减乘除数学运算了。我说的要密切注意的是`add`函数里面的`return a + b`,这步做的是这些事情: diff --git a/PythonThinking/task6-FOR、IF以及while.md b/PythonThinking/task6-FOR、IF以及while.md index 50aaefb..341cda6 100644 --- a/PythonThinking/task6-FOR、IF以及while.md +++ b/PythonThinking/task6-FOR、IF以及while.md @@ -4,36 +4,38 @@ #### 4.1.1 IF语句的使用 -```python -1 people = 20 -2 cats = 30 -3 dogs = 15 -4 -5 -6 if people < cats: -7 print("Too many cats! The world is doomed!") -8 -9 if people > cats: -10 print("Not many cats! The world is saved!") -11 -12 if people < dogs: -13 print("The world is drooled on!") -14 -15 if people > dogs: -16 print("The world is dry!") -17 -18 -19 dogs += 5 -20 -21 if people >= dogs: -22 print("People are greater than or equal to dogs.") -23 -24 if people <= dogs: -25 print("People are less than or equal to dogs.") -26 -27 -28 if people == dogs: -29 print("People are dogs.") +```{code-block} python +:linenos: + +people = 20 +cats = 30 +dogs = 15 + + +if people < cats: + print("Too many cats! The world is doomed!") + +if people > cats: + print("Not many cats! The world is saved!") + +if people < dogs: + print("The world is drooled on!") + +if people > dogs: + print("The world is dry!") + + +dogs += 5 + +if people >= dogs: + print("People are greater than or equal to dogs.") + +if people <= dogs: + print("People are less than or equal to dogs.") + + +if people == dogs: + print("People are dogs.") ```   上述代码的运行结果: @@ -100,30 +102,32 @@ People are dogs.   把我的答案和你的比较一下,然后确保你真的理解了代码块的概念。这对你进行接下来的练习很重要。把下面的代码输入进去然后运行。 -```python -1 people = 30 -2 cars = 40 -3 trucks = 15 -4 -5 -6 if cars > people: -7 print("We should take the cars.") -8 elif cars < people: -9 print("We should not take the cars.") -10 else: -11 print("We can't decide.") -12 -13 if trucks > cars: -14 print("That's too many trucks.") -15 elif trucks < cars: -16 print("Maybe we could take the trucks.") -17 else: -18 print("We still can't decide.") -19 -20 if people > trucks: -21 print("Alright, let's just take the trucks.") -22 else: -23 print("Fine, let's stay home then.") +```{code-block} python +:linenos: + +people = 30 +cars = 40 +trucks = 15 + + +if cars > people: + print("We should take the cars.") +elif cars < people: + print("We should not take the cars.") +else: + print("We can't decide.") + +if trucks > cars: + print("That's too many trucks.") +elif trucks < cars: + print("Maybe we could take the trucks.") +else: + print("We still can't decide.") + +if people > trucks: + print("Alright, let's just take the trucks.") +else: + print("Fine, let's stay home then.") ```   上述代码的运行结果: @@ -162,45 +166,47 @@ Alright, let's just take the trucks.   在上个脚本中,你写出了一个简单的问问题的测试集。在这个练习中,你将问用户一些问题,并基于他们的回答做决定。写下这个脚本,然后多玩几遍,把它弄明白。 -```python -1 print("""You enter a dark room with two doors. -2 Do you go through door #1 or door #2?""") -3 -4 door = input("> ") -5 -6 if door == "1": -7 print("There's a giant bear here eating a cheese cake.") -8 print("What do you do?") -9 print("1. Take the cake.") -10 print("2. Scream at the bear.") -11 -12 bear = input("> ") -13 -14 if bear == "1": -15 print("The bear eats your face off. Good job!") -16 elif bear == "2": -17 print("The bear eats your legs off. Good job!") -18 else: -19 print(f"Well, doing {bear} is probably better.") -20 print("Bear runs away.") -21 -22 elif door == "2": -23 print("You stare into the endless abyss at Cthulhu's retina.") -24 print("1. Blueberries.") -25 print("2. Yellow jacket clothespins.") -26 print("3. Understanding revolvers yelling melodies.") -27 -28 insanity = input("> ") -29 -30 if insanity == "1" or insanity == "2": -31 print("Your body survives powered by a mind of jello.") -32 print("Good job!") -33 else: -34 print("The insanity rots your eyes into a pool of muck.") -35 print("Good job!") -36 -37 else: -38 print("You stumble around and fall on a knife and die. Good job!") +```{code-block} python +:linenos: + +print("""You enter a dark room with two doors. + Do you go through door #1 or door #2?""") + +door = input("> ") + +if door == "1": + print("There's a giant bear here eating a cheese cake.") + print("What do you do?") + print("1. Take the cake.") + print("2. Scream at the bear.") + + bear = input("> ") + + if bear == "1": + print("The bear eats your face off. Good job!") + elif bear == "2": + print("The bear eats your legs off. Good job!") + else: + print(f"Well, doing {bear} is probably better.") + print("Bear runs away.") + +elif door == "2": + print("You stare into the endless abyss at Cthulhu's retina.") + print("1. Blueberries.") + print("2. Yellow jacket clothespins.") + print("3. Understanding revolvers yelling melodies.") + + insanity = input("> ") + + if insanity == "1" or insanity == "2": + print("Your body survives powered by a mind of jello.") + print("Good job!") + else: + print("The insanity rots your eyes into a pool of muck.") + print("Good job!") + +else: + print("You stumble around and fall on a knife and die. Good job!") ```   这里很关键的一点是在`if`语句里面又放了一个`if`语句。这在创建“嵌套”(nested)的时候非常有用,每一个分支指向另一个选择。 @@ -237,36 +243,38 @@ The bear eats your legs off. Good job! ### 4.2 FOR语句 -```python -1 the_count = [1, 2, 3, 4, 5] -2 fruits = ['apples', 'oranges', 'pears', 'apricots'] -3 change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] -4 -5 # this first kind of for-loop goes through a list -6 for number in the_count: -7 print(f"This is count {number}") -8 -9 # same as above -10 for fruit in fruits: -11 print(f"A fruit of type: {fruit}") -12 -13 # also we can go through mixed lists too -14 # notice we have to use {} since we don't know what's in it -15 for i in change: -16 print(f"I got {i}") -17 -18 # we can also build lists, first start with an empty one -19 elements = [] -20 -21 # then use the range function to do 0 to 5 counts -22 for i in range(0, 6): -23 print(f"Adding {i} to the list.") -24 # append is a function that lists understand -25 elements.append(i) -26 -27 # now we can print them out too -28 for i in elements: -29 print(f"Element was: {i}") +```{code-block} python +:linenos: + +the_count = [1, 2, 3, 4, 5] +fruits = ['apples', 'oranges', 'pears', 'apricots'] +change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] + +# this first kind of for-loop goes through a list +for number in the_count: + print(f"This is count {number}") + +# same as above +for fruit in fruits: + print(f"A fruit of type: {fruit}") + +# also we can go through mixed lists too +# notice we have to use {} since we don't know what's in it +for i in change: + print(f"I got {i}") + +# we can also build lists, first start with an empty one +elements = [] + +# then use the range function to do 0 to 5 counts +for i in range(0, 6): + print(f"Adding {i} to the list.") + # append is a function that lists understand + elements.append(i) + +# now we can print them out too +for i in elements: + print(f"Element was: {i}") ```   上述代码的运行结果: @@ -346,23 +354,25 @@ Element was: 5   在这个练习中,你要通过以下三个检查来学习`while-loop`: -```python -1 i = 0 -2 numbers = [] -3 -4 while i < 6: -5 print(f"At the top i is {i}") -6 numbers.append(i) -7 -8 i = i + 1 -9 print("Numbers now: ", numbers) -10 print(f"At the bottom i is {i}") -11 -12 -13 print("The numbers: ") -14 -15 for num in numbers: -16 print(num) +```{code-block} python +:linenos: + +i = 0 +numbers = [] + +while i < 6: + print(f"At the top i is {i}") + numbers.append(i) + + i = i + 1 + print("Numbers now: ", numbers) + print(f"At the bottom i is {i}") + + +print("The numbers: ") + +for num in numbers: + print(num) ```   上述代码的运行结果: @@ -429,84 +439,86 @@ The numbers:   目前为止你已经了解了`if`语句,函数以及列表。现在是时候深入学习一下了。照例输入如下代码,看看你能否明白程序在做什么。 -```python -1 from sys import exit -2 -3 def gold_room(): -4 print("This room is full of gold. How much do you take?") -5 -6 choice = input("> ") -7 if "0" in choice or "1" in choice: -8 how_much = int(choice) -9 else: -10 dead("Man, learn to type a number.") -11 -12 if how_much < 50: -13 print("Nice, you're not greedy, you win!") -14 exit(0) -15 else: -16 dead("You greedy bastard!") -17 -18 -19 def bear_room(): -20 print("There is a bear here.") -21 print("The bear has a bunch of honey.") -22 print("The fat bear is in front of another door.") -23 print("How are you going to move the bear?") -24 bear_moved = False -25 -26 while True: -27 choice = input("> ") -28 -29 if choice == "take honey": -30 dead("The bear looks at you then slaps your face") -31 elif choice == "taunt bear" and not bear_moved: -32 print("The bear has moved from the door.") -33 print("You can go through it now.") -34 bear_moved = True -35 elif choice == "taunt bear" and bear_moved: -36 dead("The bear gets pissed off and chews your leg.") -37 elif choice == "open door" and bear_moved: -38 gold_room() -39 else: -40 print("I got no idea what that means.") -41 -42 -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.") -46 print("Do you flee for your life or eat your head?") -47 -48 choice = input("> ") -49 -50 if "flee" in choice: -51 start() -52 elif "head" in choice: -53 dead("Well that was tasty!") -54 else: -55 cthulhu_room() -56 -57 -58 def dead(why): -59 print(why, "Good job!") -60 exit(0) -61 -62 def start(): -63 print("You are in a dark room.") -64 print("There is a door to your right and left.") -65 print("Which one do you take?") -66 -67 choice = input("> ") -68 -69 if choice == "left": -70 bear_room() -71 elif choice == "right": -72 cthulhu_room() -73 else: -74 dead("You stumble around the room until you starve.") -75 -76 -77 start() +```{code-block} python +:linenos: + +from sys import exit + +def gold_room(): + print("This room is full of gold. How much do you take?") + + choice = input("> ") + if "0" in choice or "1" in choice: + how_much = int(choice) + else: + dead("Man, learn to type a number.") + + if how_much < 50: + print("Nice, you're not greedy, you win!") + exit(0) + else: + dead("You greedy bastard!") + + +def bear_room(): + print("There is a bear here.") + print("The bear has a bunch of honey.") + print("The fat bear is in front of another door.") + print("How are you going to move the bear?") + bear_moved = False + + while True: + choice = input("> ") + + if choice == "take honey": + dead("The bear looks at you then slaps your face") + elif choice == "taunt bear" and not bear_moved: + print("The bear has moved from the door.") + print("You can go through it now.") + bear_moved = True + elif choice == "taunt bear" and bear_moved: + dead("The bear gets pissed off and chews your leg.") + elif choice == "open door" and bear_moved: + gold_room() + else: + print("I got no idea what that means.") + + +def cthulhu_room(): + print("Here you see the great evil Cthulhu.") + print("He, it, whatever stares at you and you go insane.") + print("Do you flee for your life or eat your head?") + + choice = input("> ") + + if "flee" in choice: + start() + elif "head" in choice: + dead("Well that was tasty!") + else: + cthulhu_room() + + +def dead(why): + print(why, "Good job!") + exit(0) + +def start(): + print("You are in a dark room.") + print("There is a door to your right and left.") + print("Which one do you take?") + + choice = input("> ") + + if choice == "left": + bear_room() + elif choice == "right": + cthulhu_room() + else: + dead("You stumble around the room until you starve.") + + +start() ```   上述代码的运行结果: diff --git a/PythonThinking/task7-面向对象的编程.md b/PythonThinking/task7-面向对象的编程.md index ee29d3b..a404dc5 100644 --- a/PythonThinking/task7-面向对象的编程.md +++ b/PythonThinking/task7-面向对象的编程.md @@ -4,28 +4,29 @@ ### 5.1 类的例子 -```python -1 class Song(object): #class表示要创建类,Song是类的名称, -2 -3 def __init__(self, lyrics): #称为构造方法,根据类创建对象时自动执行 -4 self.lyrics = lyrics -#根据类 Song 创建对象 -#自动执行Song类的 __init__方法 -5 -6 def sing_me_a_song(self): #定义sing_me_a_song函数 -7 for line in self.lyrics: #采用for循环获取每一句歌词 -8 print(line) #打印出来 -9 -10 happy_bday = Song(["Happy birthday to you", -11 "I don't want to get sued", -12 "So I'll stop right there"]) -13 -14 bulls_on_parade = Song(["They rally around tha family", -15 "With pockets full of shells"]) -16 -17 happy_bday.sing_me_a_song() -18 -19 bulls_on_parade.sing_me_a_song() +```{code-block} python +:linenos: + +class Song(object): #class表示要创建类,Song是类的名称, + #根据类 Song 创建对象 + #自动执行Song类的 __init__方法 + def __init__(self, lyrics): #称为构造方法,根据类创建对象时自动执行 + self.lyrics = lyrics + + def sing_me_a_song(self): #定义sing_me_a_song函数 + for line in self.lyrics: #采用for循环获取每一句歌词 + print(line) #打印出来 + +happy_bday = Song(["Happy birthday to you", + "I don't want to get sued", + "So I'll stop right there"]) + +bulls_on_parade = Song(["They rally around tha family", + "With pockets full of shells"]) + +happy_bday.sing_me_a_song() + +bulls_on_parade.sing_me_a_song() ```   上述代码的运行结果: