├── .gitignore
├── README.md
├── docs
├── Python Crash Course.pdf
├── Python编程:从入门到实践.pdf
└── README.md
└── src
├── PartII_Project_1_AlienInvasion
├── A_AlienInvasion.ipynb
├── README.md
├── alien.py
├── bullet.py
├── game_functions.py
├── game_stats.py
├── images
│ ├── alien.bmp
│ └── ship.bmp
├── settings.py
└── ship.py
├── PartII_Project_2_DataVisualization
├── A_DataVisualization.ipynb
├── README.md
├── americas.svg
├── bar_descriptions.svg
├── country_codes.py
├── death_valley_2014.csv
├── dice_visual.svg
├── dice_visual_2.svg
├── die.py
├── die_visual.svg
├── na_populations.svg
├── population_data.json
├── random_walk.py
├── randomwalk.ipynb
├── sitka_weather_07-2014.csv
├── sitka_weather_2014.csv
├── squares_plot.png
├── world_population.svg
├── world_population_3.svg
└── world_population_new3.svg
└── PartI_Basics
├── 01-起步.ipynb
├── 02-变量和简单数据类型.ipynb
├── 03-列表简介.ipynb
├── 04-操作列表.ipynb
├── 05-if语句.ipynb
├── 06-字典.ipynb
├── 07-用户输入和while循环.ipynb
├── 08-函数.ipynb
├── 09-类.ipynb
├── 10-文件和异常.ipynb
├── A_Basics_Note.ipynb
├── README.md
├── alice.txt
├── car.py
├── dataframe.xlsx
├── df2.csv
├── little_women.txt
├── name_function.py
├── numbers.json
├── pi_digits.txt
├── pi_million_digits.txt
├── pizza.py
├── programming.txt
├── siddhartha.txt
├── survey.py
├── test_94.ipynb
├── username.json
└── usernames.json
/.gitignore:
--------------------------------------------------------------------------------
1 | *.rar
2 | *.bak
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 《Python编程:从入门到实践》
2 |
3 | ### 环境
4 | - Anaconda-Jupyter
5 | - 使用:
6 | - 开始菜单打开 Jupyter Notebook;
7 | - 页面:左上角-new-Python3;
8 | - 敲代码 -- 运行
9 | - 关闭:cmd -- ctrl+c
10 | - 文件默认路径:c/uesr/administrator
11 |
12 |
13 | ### 第一部分:基础知识
14 | - [I_BASICS](https://github.com/anliux/Python-Crash-Course/tree/master/src/PartI_Basics)
15 |
16 |
17 | ### 第二部分:项目
18 | - 1、外星人入侵
19 | - [Alien Invasion](https://github.com/anliux/Python-Crash-Course/tree/master/src/PartII_Project_1_AlienInvasion)
20 | - 2、数据可视化
21 | - [Data Visualization](https://github.com/anliux/Python_Crash_Course/tree/master/src/PartII_Project_2_DataVisualization)
22 | - 3、Web Applications
23 | - [网络应用]()
24 |
25 |
26 | ## 参考教材:
27 | - 《Python编程:从入门到实践》[Reference](https://github.com/anliux/Python-Crash-Course/tree/master/docs)
28 |
29 |
30 | ### [勘误](https://nostarch.com/pythoncrashcourse)
31 |
32 |
33 | ### 参考链接
34 | - [博客园:小白Python入门](https://www.cnblogs.com/anliux/p/10233152.html)
35 |
--------------------------------------------------------------------------------
/docs/Python Crash Course.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/docs/Python Crash Course.pdf
--------------------------------------------------------------------------------
/docs/Python编程:从入门到实践.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/docs/Python编程:从入门到实践.pdf
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | ### Python Crash Course.pdf -- 英文原版
2 | ### Python编程:从入门到实践.pdf -- 中文译版
3 |
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/README.md:
--------------------------------------------------------------------------------
1 | ## AlienInvasion - <外星人入侵>
2 |
3 | ### [《笔记》](https://github.com/anliux/Python_Crash_Course/blob/master/PartII_Project_1_AlienInvasion/A_AlienInvasion.ipynb)
4 | * 基于pygame
5 | * 《笔记》为.ipybn格式,内含全部代码及相应的笔记
6 | * .ipynb文件若加载失败,可使用此链接打开 [https://nbviewer.jupyter.org/github/...](https://nbviewer.jupyter.org/github/anliux/Python_Crash_Course/blob/master/PartII_Project_1_AlienInvasion/A_AlienInvasion.ipynb)
7 |
8 | ### 目录:
9 | * 12 - 武装飞船
10 | * 13 - 外星人
11 | * 14 - 计分
12 |
13 | ### 内容摘要:
14 | * 12章:
15 | * 13章:
16 | * 14章:
17 |
18 | ### 游戏规则:
19 | #### 知识点:
20 | #### 留坑,后续进行本小项目的简介
21 | #### 注:按顺序选择从这个小项目开始的我,做得想死的心都有了,先暂留,转到下一个小项目了。以上
22 |
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/alien.py:
--------------------------------------------------------------------------------
1 | # alien.py
2 |
3 | import pygame
4 | from pygame.sprite import Sprite
5 |
6 | class Alien(Sprite):
7 | """表示单个外星人的类"""
8 |
9 | def __init__(self, ai_settings, screen):
10 | """初始化外星人并设置其起始位置"""
11 | super(Alien, self).__init__()
12 | self.screen = screen
13 | self.ai_settings = ai_settings
14 |
15 | # 加载外星人图像,并设置其rect属性
16 | self.image = pygame.image.load('images/alien.bmp')
17 | self.rect = self.image.get_rect()
18 |
19 | # 每个外星人最初都在屏幕左上角附近
20 | # 将每个外星人的左边距设置为外星人的宽度,上边距设置为外星人的高度
21 | self.rect.x = self.rect.width
22 | self.rect.y = self.rect.height
23 |
24 | # 存储外星人的准确位置
25 | self.x = float(self.rect.x)
26 |
27 | # 13.4.2-新增-检查外星人是否撞到了屏幕边缘
28 | def check_edges(self):
29 | """如果外星人位于屏幕边缘,就返回True"""
30 | screen_rect = self.screen.get_rect()
31 | if self.rect.right >= screen_rect.right:
32 | return True
33 | elif self.rect.left <= 0:
34 | return True
35 |
36 | # 13.4.1-新增-向右移动外星人-在settings.py里设置外星人速度,并在alien.py中用update()来实现
37 | def update(self):
38 | """向右或左移动外星人"""
39 | # 13.4.2-修改-为左右移动外星人,并修改下面的公式
40 | # self.x += self.ai_settings.alien_speed_factor # 使用属性self.x根据每个外星人的准确位置,这个属性可存储小数值
41 | self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) # 乘以方向,而方向是正负1,非常巧妙
42 | self.rect.x = self.x # 使用self.x的值来更新外星人的rect的位置
43 |
44 | def blitme(self):
45 | """在指定位置绘制外星人"""
46 | self.screen.blit(self.image, self.rect)
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/bullet.py:
--------------------------------------------------------------------------------
1 | # bullet.py
2 |
3 | import pygame
4 | from pygame.sprite import Sprite
5 | # 继承了从pygame.sprite中导入的Sprite类。通过使用精灵,可将游戏中相关的元素编组,进而同时操作编组中的所有元素。
6 |
7 | class Bullet(Sprite):
8 | """一个对飞船发射的子弹进行管理的类"""
9 |
10 | def __init__(self, ai_settings, screen, ship):
11 | """在飞船所处的位置创建一个子弹对象"""
12 | super(Bullet, self).__init__()
13 | self.screen = screen
14 |
15 | # 在(0,0)处创建一个表示子弹的矩形,再设置正确的位置
16 | self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
17 | ai_settings.bullet_height)
18 | self.rect.centerx = ship.rect.centerx
19 | self.rect.top = ship.rect.top
20 |
21 | # 存储用小数表示的子弹位置
22 | self.y = float(self.rect.y)
23 |
24 | # 设置子弹的颜色和速度
25 | self.color = ai_settings.bullet_color
26 | self.speed_factor = ai_settings.bullet_speed_factor
27 |
28 | def update(self):
29 | """向上移动子弹"""
30 | # 更新表示子弹位置的小数值
31 | self.y -= self.speed_factor
32 |
33 | # 更新表示子弹的rect的位置
34 | self.rect.y = self.y
35 |
36 | def draw_bullet(self):
37 | """在屏幕上绘制子弹"""
38 | pygame.draw.rect(self.screen, self.color, self.rect)
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/game_functions.py:
--------------------------------------------------------------------------------
1 | # game_functions.py
2 |
3 | # 创建了两个新函数:check_keydown_events() 和check_keyup_events() ,它们都包含形参event 和ship
4 | # 将函数check_events 中相应的代码替换成了对这两个函数的调用。
5 |
6 | import sys
7 |
8 | # 13.6.2-新增-响应外星人和飞船的碰撞-使用sleep来暂停游戏
9 | from time import sleep
10 |
11 | import pygame
12 |
13 | # 12.8.4开火-新增
14 | from bullet import Bullet
15 |
16 | # 13.3.3-新增-创建外星人群
17 | from alien import Alien
18 |
19 | def check_keydown_events(event, ai_settings, screen, ship, bullets):
20 | # 12.8.4-开火-将ai_settings,screen,bullets加入参数列表
21 | """响应按键"""
22 | if event.key == pygame.K_RIGHT: # 读取属性event.key,以检查按下的是否是右箭头键
23 | # 12.6.2新增:修改了玩家按下右箭头键时响应的方式--不直接调整飞船的位置,而是将moving_right设置为True
24 | ship.moving_right = True
25 | # 向右移动飞船
26 | # ship.rect.centerx += 1 # 如果按下的是右箭头键,就将ship.rect.centerx的值加1,从而将飞船向右移动
27 | # 12.6.3新增:左右移动
28 | elif event.key == pygame.K_LEFT:
29 | ship.moving_left = True
30 |
31 | # 12.8.4-开火-新增
32 | elif event.key == pygame.K_SPACE:
33 | # 12.8.8-新增-将发射子弹的代码移到独立函数中,放到下面
34 | fire_bullet(ai_settings, screen, ship, bullets)
35 | # 创建一颗子弹,并将其加入到编组bullets中
36 | # 12.8.6-新增-限制子弹数量
37 | # if len(bullets) < ai_settings.bullets_allowed:
38 | # new_bullet = Bullet(ai_settings, screen, ship)
39 | # bullets.add(new_bullet)
40 |
41 | def check_keyup_events(event, ship):
42 | """响应松开"""
43 | if event.key == pygame.K_RIGHT:
44 | ship.moving_right = False
45 | # 12.6.3新增
46 | elif event.key == pygame.K_LEFT:
47 | ship.moving_left = False
48 |
49 | def check_events(ai_settings, screen, ship, bullets): # 1-新增:在函数check_events()中包含形参ship
50 | # 13.1-新增-将event加入参数列表,并在主程序响应添加event参数 - 报错,先删了event并注释13.1添加的按键Q退出程序
51 | # 12.8.4-开火-新增:将ai_settings, screen, bullet加入参数列表
52 | # check_events()函数:存放管理事件的代码,以简化run_game()并隔离事件管理循环。
53 | """响应按键和鼠标事件"""
54 | for event in pygame.event.get():
55 | if event.type == pygame.QUIT:
56 | pygame.quit() # 别忘了这句
57 | sys.exit()
58 | elif event.type == pygame.KEYDOWN: # 添加elif代码块,以便在pygame检查到KEYDOWN事件时作出相应
59 | check_keydown_events(event, ai_settings, screen, ship, bullets)
60 | # 12.8.4-开火-新增ai_settings, screen, bullets到参数列表
61 |
62 | # 12.6.2新增:添加一个elif代码块,用于响应KEYUP事件
63 | elif event.type == pygame.KEYUP:
64 | check_keyup_events(event, ship)
65 |
66 | # 13.1新增-结束游戏的快捷键Q
67 | # elif event.key == pygame.K_q:
68 | # pygame.quit()
69 | # sys.exit()
70 |
71 | # 12.8.8-新增-将发射子弹的代码放在下面的独立函数中
72 | def fire_bullet(ai_settings, screen, ship, bullets):
73 | """如果还没达到限制,就发射一颗子弹"""
74 | # 创建新子弹,并将其加入到编组bullets中
75 | if len(bullets) < ai_settings.bullets_allowed:
76 | new_bullet = Bullet(ai_settings, screen, ship)
77 | bullets.add(new_bullet)
78 |
79 | def update_screen(ai_settings, screen, ship, bullets, aliens):
80 | # 13.3.2-创建多行外星人中,将alien改为aliens
81 | # 13.2.3-让外星人出现在屏幕上-添加alien到参数列表
82 | # 12.8.4新增-bullets到参数列表
83 | # update_screen()函数:存放更新屏幕的代码
84 | """更新屏幕上的图像,并切换到新屏幕"""
85 | # 每次循环都重新绘制屏幕
86 | screen.fill(ai_settings.bg_color)
87 |
88 | # 12.8.4-开火-新增:在飞船和外星人后面重绘所有子弹
89 | # 为在屏幕上绘制发射的所有子弹,遍历编组bullets中的精灵,并对每个精灵都调用draw_bullet()
90 | for bullet in bullets.sprites():
91 | bullet.draw_bullet()
92 |
93 | ship.blitme()
94 | # 13.2.3-新增-为让外星人出现在屏幕上,在update_screen()中调用方法blitme()
95 | # alien.blitme() # 先绘制子弹和飞船,再绘制外星人。在13.3.2中注释,并补充下一句
96 | aliens.draw(screen) # 对编组调用draw()时,pygame将自动绘制编组的每个元素,绘制位置由元素的属性rect决定
97 | # 这里:aliens.draw(screen)在屏幕上绘制编组中的每个外星人
98 |
99 | # 让最近绘制的屏幕可见
100 | pygame.display.flip()
101 |
102 | # 12.8.7 新增-创建函数update_bullets()并删去主程序中响应的部分
103 | # 13.5.3-大修-添加参数列表,并增加if判断
104 | def update_bullets(ai_settings, screen, ship, aliens, bullets):
105 | """更新子弹的位置,并删除已消失的子弹"""
106 | # 更新子弹的位置
107 | bullets.update()
108 |
109 | # 删除已消失的子弹
110 | for bullet in bullets.copy():
111 | if bullet.rect.bottom <= 0:
112 | bullets.remove(bullet)
113 |
114 | # 13.5.1-新增-检测子弹与外星人的碰撞
115 | # 检测是否有子弹击中了外星人,如果是,就删除相应的子弹和外星人
116 | # 13.5.5-重构时移到到另一个(下面那个)函数中
117 | # collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
118 | # 新增的这行代码遍历编组bullets 中的每颗子弹,再遍历编组aliens 中的每个外星人。
119 | # 每当有子弹和外星人的rect 重叠时,groupcollide() 就在它返回的字典中添加一个键-值对。
120 | # 两个实参True 告诉Pygame删除发生碰撞的子弹和外星人。
121 | # (要模拟能够穿行到屏幕顶端的高能子弹——消灭它击中的每个外星人,可将第一个布尔实参设置为False ,并让第二个布尔实参为True 。
122 | # 这样被击中的外星人将消失,但所有的子弹都始终有效,直到抵达屏幕顶端后消失。)
123 |
124 | # 13.5.3-新增-生成新的外星人群
125 | # 13.5.5-重构时移到到另一个(下面那个)函数中
126 | # if len(aliens) == 0:
127 | # 删除现有的子弹并新建一群外星人
128 | # bullets.empty() # 为空时,用方法empty()删除编组中余下的所有精灵,从而删除现有的所有子弹
129 | # create_fleet(ai_settings, screen, ship, aliens)
130 |
131 | # 13.5.5-重构-上面语句移到新函数后调用
132 | check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets)
133 |
134 | # 13.5.5-重构update_bullets()-创建了一个新函数——check_bullet_alien_collisions()
135 | def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
136 | """响应子弹与外星人的碰撞"""
137 | # 删除发送碰撞的子弹和外星人
138 | collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
139 |
140 | if len(aliens) == 0:
141 | # 删除现有的所有子弹,并创建一个新的外星人群
142 | bullets.empty()
143 | create_fleet(ai_settings, screen, ship, aliens)
144 |
145 |
146 | # 13.3.4-重构create_fleet()-新增函数
147 | def get_number_aliens_x(ai_settings, alien_width):
148 | """计算每行可容纳多少个外星人"""
149 | available_space_x = ai_settings.screen_width - 2 * alien_width
150 | number_aliens_x = int(available_space_x / (2 * alien_width))
151 | return number_aliens_x
152 |
153 | # 13.3.5-添加行-新增函数
154 | def get_number_rows(ai_settings, ship_height, alien_height):
155 | """计算屏幕可容纳多少行外星人"""
156 | available_space_y = (ai_settings.screen_height -
157 | (3 * alien_height) - ship_height)
158 | number_rows = int(available_space_y / (2 * alien_height))
159 | return number_rows
160 |
161 | # 13.3.4-重构create_fleet()-新增函数
162 | def create_alien(ai_settings, screen, aliens, alien_number, row_number):
163 | # 13.3.5-新增row_number到参数列表
164 | """创建一个外星人并将其放在当前行"""
165 | alien = Alien(ai_settings, screen)
166 | alien_width = alien.rect.width
167 | # 13.3.5新增
168 | alien.x = alien_width + 2 * alien_width * alien_number
169 | alien.rect.x = alien.x
170 | # 13.3.5新增
171 | alien.rect.y = alien.rect.height = 2 * alien.rect.height * row_number
172 | aliens.add(alien)
173 |
174 | # 13.3.4-重构create_fleet()-重构
175 | # 13.3.3-新增的一个功能
176 | def create_fleet(ai_settings, screen, ship, aliens):
177 | # 13.3.5新增ship到参数列表
178 | """创建外星人群"""
179 | # 创建一个外星人,并计算一行可容纳多少个外星人
180 | # 外星人间距为外星人宽度
181 | alien = Alien(ai_settings, screen) # 这个外星人不是外星人群的成员,没有将它加入到编组aliens中
182 | # alien_width = alien.rect.width # 从外星人的rect属性中获取宽度,并存储这个值,以免反复访问rect
183 | # available_space_x = ai_settings.screen_width - 2*alien_width # 计算可用于放置外星人的水平空间,以及人数
184 | # number_aliens_x = int(available_space_x / (2*alien_width)) # 使用int确保外星人的人数是整数。int()将小数部分丢弃
185 | number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
186 | # 13.3.5新增
187 | number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
188 |
189 | # 创建第一行外星人-13.3.5注释,放进下方包括行的for循环中
190 | # for alien_number in range(number_aliens_x): # 从0到要创建的外星人的数量
191 | # 创建一个外星人并通过设置x坐标将其加入当前行
192 | # alien = Alien(ai_settings, screen)
193 | # alien.x = alien_width + 2 * alien_width * alien_number #将每个外星人往右推一个外星人的宽度
194 | # alien.rect.x = alien.x
195 | # aliens.add(alien) # 将每个新创建的外星人都添加到编组aliens中
196 | # 13.3.5注释
197 | # create_alien(ai_settings, screen, aliens, alien_number)
198 |
199 | # 13.3.5新增-创建外星人群
200 | for row_number in range(number_rows):
201 | for alien_number in range(number_aliens_x):
202 | create_alien(ai_settings, screen, aliens, alien_number, row_number)
203 |
204 | # 13.4.4-新增:编写函数check_fleet_edges() 和change_fleet_direction() ,并对update_aliens() 进行修改:
205 | def check_fleet_edges(ai_settings, aliens):
206 | """有外星人到达边缘时采取相应的措施"""
207 | for alien in aliens.sprites():
208 | if alien.check_edges():
209 | change_fleet_direction(ai_settings, aliens)
210 | break
211 |
212 | # 13.4.4新增-同上
213 | def change_fleet_direction(ai_settings, aliens):
214 | """将整群外星人下移,并改变它们的方向"""
215 | for alien in aliens.sprites():
216 | alien.rect.y += ai_settings.fleet_drop_speed
217 | ai_settings.fleet_direction *= -1
218 |
219 | # 13.6.2-新增-响应外星人和飞船的碰撞
220 | def ship_hit(ai_setting, stats, screen, ship, aliens, bullets):
221 | """响应被外星人撞到的飞船"""
222 | # 将ships_left减一
223 | # 13.6.4-新增-游戏结束响应-增加if-else语句
224 | if stats.ships_left > 0:
225 | stats.ships_left -= 1
226 |
227 | # 清空外星人列表和子弹列表
228 | aliens.empty()
229 | bullets.empty()
230 |
231 | # 创建一群新的外星人,并将飞船放到屏幕底部中央
232 | create_fleet(ai_setting, screen, ship, aliens)
233 | ship.center_ship()
234 |
235 | # 暂停
236 | sleep(0.5)
237 |
238 | else:
239 | stats.game_active = False
240 |
241 | # 13.6.3-新增函数-有外星人达到屏幕底端
242 | def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):
243 | """检查是否有外星人到达了屏幕底端"""
244 | screen_rect = screen.get_rect()
245 | for alien in aliens.sprites():
246 | if alien.rect.bottom >= screen_rect.bottom:
247 | # 像飞船被撞到一样进行处理
248 | ship_hit(ai_settings, stats, screen, ship, aliens, bullets)
249 | break
250 |
251 | # 13.4.1-新增-向右移动外星人
252 | # 13.6.2-新增-响应外星人和飞船的碰撞-添加ai_settings,stats,screen,ship,bullets到参数列表
253 | def update_aliens(ai_settings, stats, ship, aliens, bullets):
254 | """更新外星人群众所有外星人的位置"""
255 | """
256 | 13.4.4新增-检查是否有外星人位于屏幕边缘,并更新整群外星人的位置
257 | """
258 | check_fleet_edges(ai_settings, aliens)
259 | aliens.update()
260 |
261 | # 13.6.1-新增-检测外星人和飞船碰撞
262 | if pygame.sprite.spritecollideany(ship, aliens): # spritecollideany()接受两个实参:一个精灵一个编组
263 | # 检查编组是否有成员与精灵碰撞,并在找到与精灵发送了碰撞的成员后就停止遍历编组
264 | # print('Ship hit!!!')
265 | ship_hit(ai_settings, stats, screen, ship, aliens, bullets)
266 |
267 | # 13.6.3-新增-有外星人达到屏幕底端-调用
268 | check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/game_stats.py:
--------------------------------------------------------------------------------
1 | # game_stats.py
2 |
3 | class GameStats():
4 | """跟踪游戏的统计信息"""
5 |
6 | def __init__(self, ai_settings):
7 | """初始化统计信息"""
8 | self.ai_settings = ai_settings
9 | self.reset_stats() # 在方法reset_stats()中初始化大部分统计信息,而不是在__init__()中直接初始化他们
10 |
11 | # 13.6.4-新增-结束游戏
12 | self.game_active = True
13 |
14 | def reset_stats(self):
15 | """初始化在游戏运行期间可能变化的统计信息"""
16 | self.ships_left = self.ai_settings.ship_limit # ships_left -其值在游戏运行期间将不断变化。
17 | #一开始玩家拥有的飞船数存储在settings.py的ship_limit 中:
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/images/alien.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/src/PartII_Project_1_AlienInvasion/images/alien.bmp
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/images/ship.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/src/PartII_Project_1_AlienInvasion/images/ship.bmp
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/settings.py:
--------------------------------------------------------------------------------
1 | # settings.py
2 | # 用于将所有设置存储在一个地方,让代码调用更简单,且在项目增大时修改游戏的外观更容易
3 |
4 | class Settings():
5 | """存储《外星人入侵》的所有设置的类"""
6 |
7 | def __init__(self):
8 | """初始化游戏的设置"""
9 | # 屏幕设置
10 | self.screen_width = 1200
11 | self.screen_height = 800
12 | self.bg_color = (230, 230, 230)
13 |
14 | # 12.6.4新增-调整飞船的速度
15 | self.ship_speed_factor = 1.5 # 改为每次移动1.5像素
16 | # 然而rect的centerx等属性只能存储整数值,因此对Ship类做些修改
17 |
18 | # 13.6.2-新增-响应外星人和飞船碰撞
19 | self.ship_limit = 3
20 |
21 | # 12.8.1新增-子弹设置
22 | # 创建宽3像素,高15像素的深灰色子弹,子弹的速度比飞船稍低
23 | # 13.5.4-提高子弹速度-修改子弹速度从1改为3
24 | self.bullet_speed_factor = 3
25 | self.bullet_width = 3
26 | self.bullet_height = 15
27 | self.bullet_color = 60, 60, 60
28 | # 12.8.6新增-限制子弹数量-将未消失的子弹数限制为3
29 | self.bullets_allowed = 3
30 |
31 | # 13.4.1-新增-向右移动外星人-添加一个控制外星人速度的设置:
32 | self.alien_speed_factor = 1
33 |
34 | # 13.4.2-新增-创建表示外星人移动方向的设置
35 | self.fleet_drop_speed = 10
36 | self.fleet_direction = 1
37 | # fleet_direction为1表示向右移,为-1表示向左移
--------------------------------------------------------------------------------
/src/PartII_Project_1_AlienInvasion/ship.py:
--------------------------------------------------------------------------------
1 | # ship.py
2 |
3 | import pygame
4 |
5 | class Ship():
6 |
7 | def __init__(self, ai_settings, screen): # 后一个参数screen指定了要将飞船绘制到什么地方
8 | # 12.6.4新增-添加ai_settings,让飞船能够获取其速度设置
9 |
10 | """初始化飞船并设置其初始位置"""
11 | self.screen = screen
12 |
13 | # 12.6.4新增-将形参ai_settings的值存储在一个属性中,以便能够在update()中使用它
14 | self.ai_settings = ai_settings
15 |
16 | # 加载飞船图像并获取其外接矩形
17 | self.image = pygame.image.load('images/ship.bmp') # 这个load函数返回一个表示飞船的surface,并存储到self.image中
18 | self.rect = self.image.get_rect() # 使用get_rect()获取响应surface的属性rect
19 | # 处理rect对象时,可使用矩形四角和中心的x和y坐标,通过设置这些值来指定矩形的位置
20 | # 居中:center,centerx,centery 与屏幕边缘对齐:top,bottom,left,right 等等
21 | self.screen_rect = screen.get_rect() # 首先将表示屏幕的矩形存储在self.screen_rect中
22 |
23 | # 将每艘新飞船放在屏幕底部中央
24 | self.rect.centerx = self.screen_rect.centerx # 将self.rect.centerx(飞船中心的x坐标)设置为表示屏幕的矩形的属性centerx
25 | self.rect.bottom = self.screen_rect.bottom # 将self.rect.bottom(飞船下边缘的y坐标)设置为表示屏幕的矩形的属性bottom
26 |
27 | # 12.6.4新增-在飞船的属性center中存储小数值
28 | self.center = float(self.rect.centerx)
29 |
30 | # 12.6.2新增:移动标志
31 | self.moving_right = False
32 | # 12.6.3新增:左右移动
33 | self.moving_left = False
34 |
35 | # 12.6.2新增
36 | def update(self):
37 | """根据移动标志调整飞船的位置"""
38 | # 12.6.5 修改:更新飞船的center值,而不是rect
39 | # 12.6.5-在修改self.center前检查飞船的位置。self.rect.right返回飞船外接矩形的右边缘的x坐标
40 | # 如果这个值小于self.screen_rect.right的值,就说明飞船未触及屏幕右边缘
41 | # if self.moving_right:
42 | if self.moving_right and self.rect.right < self.screen_rect.right:
43 | # self.rect.centerx += 1
44 | # 12.6.4修改上一句为:
45 | self.center += self.ai_settings.ship_speed_factor
46 |
47 | # 12.6.3新增:左右移动
48 | # 12.6.5新增:左边缘类似:如果rect的左边缘x坐标大于0,就说明飞船未触及屏幕左边缘
49 | # if self.moving_left:
50 | if self.moving_left and self.rect.left > 0:
51 | # self.rect.centerx -= 1
52 | # 同上,12.6.4修改为
53 | self.center -= self.ai_settings.ship_speed_factor
54 |
55 | # 12.6.4新增:根据self.center更新rect对象
56 | # 更新self.center后,再根据它来更新控制飞船位置的self.rect.centerx,self.rect.centerx将只存储self.center的整数部分
57 | self.rect.centerx = self.center
58 |
59 | def blitme(self):
60 | """在指定位置绘制飞船"""
61 | self.screen.blit(self.image, self.rect)
62 |
63 | # 13.6.2-响应外星人和飞船碰撞-新增函数
64 | def center_ship(self):
65 | """让飞船在屏幕上居中"""
66 | self.center = self.screen_rect.centerx
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/README.md:
--------------------------------------------------------------------------------
1 | ## DataVisualization - <数据可视化>
2 |
3 | ### [《笔记》](https://github.com/anliux/Python_Crash_Course/blob/master/PartII_Project_1_AlienInvasion/A_AlienInvasion.ipynb)
4 | * 《笔记》为.ipybn格式,内含全部代码及相应的笔记
5 | * .ipynb文件若加载失败,可使用此链接打开 [https://nbviewer.jupyter.org/github/...](https://nbviewer.jupyter.org/github/anliux/Python_Crash_Course/blob/master/PartII_Project_2_DataVisualization/A_DataVisualization.ipynb)
6 |
7 | ### 目录:
8 | * 15 - 生成数据
9 | * 16 - 下载数据
10 | * 17 - 使用API
11 |
12 | ### 内容摘要:
13 | * 15章:
14 | * 16章:
15 | * 17章:
16 |
17 | ### 注:
18 | * 15.3 随机漫步显示报错,效果图放在新建的 randomwalk.ipynb 文件中
19 | * 其他..
20 |
21 | * 好久不更新这个仓库了,划个水吧。。哈哈
22 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/bar_descriptions.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/country_codes.py:
--------------------------------------------------------------------------------
1 | # country_codes.py
2 | from pygal_maps_world.i18n import COUNTRIES
3 |
4 | def get_country_code(country_name):
5 | """根据指定的国家,返回pygal使用的两个字母的国别码"""
6 | for code, name in COUNTRIES.items():
7 | if name == country_name:
8 | return code
9 | # 如果没有找到指定的国家,就返回None
10 | return None
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/dice_visual.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/dice_visual_2.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/die.py:
--------------------------------------------------------------------------------
1 | # die.py
2 |
3 | from random import randint
4 |
5 | class Die():
6 | """表示一个骰子的类"""
7 |
8 | def __init__(self, num_sides=6): # 创建实例时,若没有指定任何实参,面数默认为6
9 | """骰子默认为6面"""
10 | self.num_sides = num_sides
11 |
12 | def roll(self):
13 | """返回一个位于1和骰子面数之间的随机值"""
14 | return randint(1, self.num_sides)
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/die_visual.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/random_walk.py:
--------------------------------------------------------------------------------
1 | # random_walk.py
2 | from random import choice # 每次做决策时都是用choice()来决定使用哪种选择
3 |
4 | class RandomWalk():
5 | """一个生产随机漫步数据的类"""
6 |
7 | def __init__(self, num_points=5000):
8 | """初始化随机漫步的属性"""
9 | self.num_points = num_points
10 |
11 | # 所有随机漫步都始于(0,0)
12 | # 创建两个用于存储x和y值的列表,并让每次漫步都从(0,0)出发
13 | self.x_values = [0]
14 | self.y_values = [0]
15 |
16 | # 15.3.2新增:def fill_walk()
17 | def fill_walk(self):
18 | """计算随机漫步包含的所有点"""
19 |
20 | # 不断漫步,直到列表达到指定的长度
21 | # 这个方法的主要部分告诉Python如何模拟四种漫步决定:向右走还是向左走?沿指定的方向走多远?
22 | # 向上走还是向下走?沿选定的方向走多远?
23 | while len(self.x_values) < self.num_points:
24 |
25 | # 决定前进方向以及沿这个方向前进的距离
26 | x_direction = choice([1, -1]) # 方向:要么向右1,要么向左-1
27 | x_distance = choice([0, 1, 2, 3, 4]) # 距离:0-4选择沿指定方向走多远
28 | # 距离0:沿某轴移动
29 | x_step = x_direction * x_distance # 确定沿x轴移动的距离
30 |
31 | y_direction = choice([1, -1])
32 | y_distance = choice([0, 1, 2, 3, 4])
33 | y_step = y_direction * y_distance # 确定沿y轴移动的距离
34 |
35 | # 拒绝原地踏步:两个step都是0意味着原地踏步,这时continue继续循环
36 | if x_step == 0 and y_step == 0:
37 | continue
38 |
39 | # 计算下一个点的x和y值
40 | # 将step与values中的最后一个数即[-1]相加,得到下一个点的值
41 | next_x = self.x_values[-1] + x_step
42 | next_y = self.y_values[-1] + y_step
43 |
44 | # 将下一个点的值附加到x和y值列表的后面
45 | self.x_values.append(next_x)
46 | self.y_values.append(next_y)
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/sitka_weather_07-2014.csv:
--------------------------------------------------------------------------------
1 | AKDT,Max TemperatureF,Mean TemperatureF,Min TemperatureF,Max Dew PointF,MeanDew PointF,Min DewpointF,Max Humidity, Mean Humidity, Min Humidity, Max Sea Level PressureIn, Mean Sea Level PressureIn, Min Sea Level PressureIn, Max VisibilityMiles, Mean VisibilityMiles, Min VisibilityMiles, Max Wind SpeedMPH, Mean Wind SpeedMPH, Max Gust SpeedMPH,PrecipitationIn, CloudCover, Events, WindDirDegrees
2 | 2014-7-1,64,56,50,53,51,48,96,83,58,30.19,30.00,29.79,10,10,10,7,4,,0.00,7,,337
3 | 2014-7-2,71,62,55,55,52,46,96,80,51,29.81,29.75,29.66,10,9,2,13,5,,0.14,7,Rain,327
4 | 2014-7-3,64,58,53,55,53,51,97,85,72,29.88,29.86,29.81,10,10,8,15,4,,0.01,6,,258
5 | 2014-7-4,59,56,52,52,51,50,96,88,75,29.91,29.89,29.87,10,9,2,9,2,,0.07,7,Rain,255
6 | 2014-7-5,69,59,50,52,50,46,96,72,49,29.88,29.82,29.79,10,10,10,13,5,,0.00,6,,110
7 | 2014-7-6,62,58,55,51,50,46,80,71,58,30.13,30.07,29.89,10,10,10,20,10,29,0.00,6,Rain,213
8 | 2014-7-7,61,57,55,56,53,51,96,87,75,30.10,30.07,30.05,10,9,4,16,4,25,0.14,8,Rain,211
9 | 2014-7-8,55,54,53,54,53,51,100,94,86,30.10,30.06,30.04,10,6,2,12,5,23,0.84,8,Rain,159
10 | 2014-7-9,57,55,53,56,54,52,100,96,83,30.24,30.18,30.11,10,7,2,9,5,,0.13,8,Rain,201
11 | 2014-7-10,61,56,53,53,52,51,100,90,75,30.23,30.17,30.03,10,8,2,8,3,,0.03,8,Rain,215
12 | 2014-7-11,57,56,54,56,54,51,100,94,84,30.02,30.00,29.98,10,5,2,12,5,,1.28,8,Rain,250
13 | 2014-7-12,59,56,55,58,56,55,100,97,93,30.18,30.06,29.99,10,6,2,15,7,26,0.32,8,Rain,275
14 | 2014-7-13,57,56,55,58,56,55,100,98,94,30.25,30.22,30.18,10,5,1,8,4,,0.29,8,Rain,291
15 | 2014-7-14,61,58,55,58,56,51,100,94,83,30.24,30.23,30.22,10,7,0,16,4,,0.01,8,Fog,307
16 | 2014-7-15,64,58,55,53,51,48,93,78,64,30.27,30.25,30.24,10,10,10,17,12,,0.00,6,,318
17 | 2014-7-16,61,56,52,51,49,47,89,76,64,30.27,30.23,30.16,10,10,10,15,6,,0.00,6,,294
18 | 2014-7-17,59,55,51,52,50,48,93,84,75,30.16,30.04,29.82,10,10,6,9,3,,0.11,7,Rain,232
19 | 2014-7-18,63,56,51,54,52,50,100,84,67,29.79,29.69,29.65,10,10,7,10,5,,0.05,6,Rain,299
20 | 2014-7-19,60,57,54,55,53,51,97,88,75,29.91,29.82,29.68,10,9,2,9,2,,0.00,8,,292
21 | 2014-7-20,57,55,52,54,52,50,94,89,77,29.92,29.87,29.78,10,8,2,13,4,,0.31,8,Rain,155
22 | 2014-7-21,69,60,52,53,51,50,97,77,52,29.99,29.88,29.78,10,10,10,13,4,,0.00,5,,297
23 | 2014-7-22,63,59,55,56,54,52,90,84,77,30.11,30.04,29.99,10,10,10,9,3,,0.00,6,Rain,240
24 | 2014-7-23,62,58,55,54,52,50,87,80,72,30.10,30.03,29.96,10,10,10,8,3,,0.00,7,,230
25 | 2014-7-24,59,57,54,54,52,51,94,84,78,29.95,29.91,29.89,10,9,3,17,4,28,0.06,8,Rain,207
26 | 2014-7-25,57,55,53,55,53,51,100,92,81,29.91,29.87,29.83,10,8,2,13,3,,0.53,8,Rain,141
27 | 2014-7-26,57,55,53,57,55,54,100,96,93,29.96,29.91,29.87,10,8,1,15,5,24,0.57,8,Rain,216
28 | 2014-7-27,61,58,55,55,54,53,100,92,78,30.10,30.05,29.97,10,9,2,13,5,,0.30,8,Rain,213
29 | 2014-7-28,59,56,53,57,54,51,97,94,90,30.06,30.00,29.96,10,8,2,9,3,,0.61,8,Rain,261
30 | 2014-7-29,61,56,51,54,52,49,96,89,75,30.13,30.02,29.95,10,9,3,14,4,,0.25,6,Rain,153
31 | 2014-7-30,61,57,54,55,53,52,97,88,78,30.31,30.23,30.14,10,10,8,8,4,,0.08,7,Rain,160
32 | 2014-7-31,66,58,50,55,52,49,100,86,65,30.31,30.29,30.26,10,9,3,10,4,,0.00,3,,217
33 |
--------------------------------------------------------------------------------
/src/PartII_Project_2_DataVisualization/squares_plot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/src/PartII_Project_2_DataVisualization/squares_plot.png
--------------------------------------------------------------------------------
/src/PartI_Basics/01-起步.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第一章 起步"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": 3,
13 | "metadata": {},
14 | "outputs": [
15 | {
16 | "name": "stdout",
17 | "output_type": "stream",
18 | "text": [
19 | "hello python world\n"
20 | ]
21 | }
22 | ],
23 | "source": [
24 | "# hello_world.py\n",
25 | "print('hello python world')"
26 | ]
27 | }
28 | ],
29 | "metadata": {
30 | "kernelspec": {
31 | "display_name": "Python 3",
32 | "language": "python",
33 | "name": "python3"
34 | },
35 | "language_info": {
36 | "codemirror_mode": {
37 | "name": "ipython",
38 | "version": 3
39 | },
40 | "file_extension": ".py",
41 | "mimetype": "text/x-python",
42 | "name": "python",
43 | "nbconvert_exporter": "python",
44 | "pygments_lexer": "ipython3",
45 | "version": "3.7.0"
46 | }
47 | },
48 | "nbformat": 4,
49 | "nbformat_minor": 2
50 | }
51 |
--------------------------------------------------------------------------------
/src/PartI_Basics/02-变量和简单数据类型.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第二章 变量和简单数据类型\n",
8 | "\n",
9 | "知识点:认识变量、变量名规则、单双引号、字符串(大小写、拼接、空白)、数字(简单计算-除法、次方)、注释(单行多行)"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "## 2.1 变量\n",
17 | "\n",
18 | "### python变量名:\n",
19 | "大写无妨,尽量用小写,字母数字下划线,数字不能开头,中间不能空格,并且慎用小写字母L和大写字母O(与数字0,1非常相似)\n",
20 | "\n",
21 | "### Python约定的文件名:\n",
22 | "使用小写字母和下划线"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": 5,
28 | "metadata": {},
29 | "outputs": [
30 | {
31 | "name": "stdout",
32 | "output_type": "stream",
33 | "text": [
34 | "Hello Python World!\n",
35 | "Hello Python Crash Course World!\n"
36 | ]
37 | }
38 | ],
39 | "source": [
40 | "# 变量\n",
41 | "# hello_world.py\n",
42 | "\n",
43 | "message = 'Hello Python World!'\n",
44 | "print(message)\n",
45 | "\n",
46 | "message = 'Hello Python Crash Course World!'\n",
47 | "print(message)"
48 | ]
49 | },
50 | {
51 | "cell_type": "markdown",
52 | "metadata": {},
53 | "source": [
54 | "## 2.2 字符串\n",
55 | "\n",
56 | "### 单引号双引号均可,灵活使用有助于撇号的使用,单双均可在外"
57 | ]
58 | },
59 | {
60 | "cell_type": "markdown",
61 | "metadata": {},
62 | "source": [
63 | "### 小结:\n",
64 | "\n",
65 | "#### title() - 改为首字母大写、其余小写\n",
66 | "#### upper() - 改为所有字母大写\n",
67 | "#### lower() - 改为所有字母小写\n",
68 | "#### + :拼接字符串\n",
69 | "#### 制表符:\\t\n",
70 | "#### 换行: \\n\n",
71 | "#### strip() - 删除空白\n",
72 | "#### rstrip() - 删除右边的空白\n",
73 | "#### lstrip() - 删除左边的空白\n",
74 | "#### 单双引号的灵活使用:普通用单;双嵌套单,英语中常用的缩写一撇等等"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": 120,
80 | "metadata": {
81 | "scrolled": true
82 | },
83 | "outputs": [
84 | {
85 | "name": "stdout",
86 | "output_type": "stream",
87 | "text": [
88 | "Ada Lovelace\n",
89 | "ADA LOVELACE\n",
90 | "ada lovelace\n",
91 | "ada lovelace\n",
92 | "Hello,Ada Lovelace!\n",
93 | "Hello,Ada Lovelace!\n",
94 | "\tPython\n",
95 | "Language:\n",
96 | "Python\n",
97 | "C\n",
98 | "JavaScript\n",
99 | "Language:\n",
100 | "\tPython\n",
101 | "\tC\n",
102 | "\tJavaScript\n",
103 | " Python\n"
104 | ]
105 | }
106 | ],
107 | "source": [
108 | "# 字符串\n",
109 | "# name.py\n",
110 | "\n",
111 | "\n",
112 | "# 字符串大小写\n",
113 | "name = 'ADA loVelace'\n",
114 | "print(name.title()) # title() - 改为首字母大写、其余小写\n",
115 | "print(name.upper()) # upper() - 改为所有字母大写\n",
116 | "print(name.lower()) # lower() - 改为所有字母小写,很有用\n",
117 | "\n",
118 | "\n",
119 | "\n",
120 | "# 字符串合并/拼接\n",
121 | "first_name = 'ada'\n",
122 | "last_name = 'lovelace'\n",
123 | "full_name = first_name + ' ' + last_name # ''里的是姓和名之间的空格\n",
124 | " # +合并字符串:拼接\n",
125 | "print(full_name) # 简单输出拼接成的全名\n",
126 | "print('Hello,' + full_name.title() + '!') # 使用全名并设置为合适的格式,以显示一条格式良好的问候语\n",
127 | "\n",
128 | "# 或者使用拼接来创建消息,并把整条消息存储在一个变量中\n",
129 | "message = 'Hello,' + full_name.title() + '!'\n",
130 | "print(message)\n",
131 | "\n",
132 | "\n",
133 | "\n",
134 | "# 字符串添加空白 - 制表符或换行\n",
135 | "# 制表符:\\t\n",
136 | "# 换行: \\n\n",
137 | "print('\\tPython') # 行首制表符\n",
138 | "print('Language:\\nPython\\nC\\nJavaScript') # 换号(不过可读性可真差。。。)\n",
139 | "print('Language:\\n\\tPython\\n\\tC\\n\\tJavaScript') # 同时包含制表符和换行符 - 使用单行字符串生成四行输出\n",
140 | "\n",
141 | "\n",
142 | "\n",
143 | "# 字符串删除空白\n",
144 | "# 方法:strip() - 删除空白;rstrip() - 删除右边的空白;lstrip() - 删除左边的空白\n",
145 | "favorite_language = ' Python '\n",
146 | "print(favorite_language.rstrip()) # 这种只是暂时删除,下次用到还是有空格。永久删除需要将删除空格后的值存储在变量中"
147 | ]
148 | },
149 | {
150 | "cell_type": "code",
151 | "execution_count": 21,
152 | "metadata": {},
153 | "outputs": [
154 | {
155 | "name": "stdout",
156 | "output_type": "stream",
157 | "text": [
158 | "One of Python's strengths is its diverse community.\n"
159 | ]
160 | }
161 | ],
162 | "source": [
163 | "# 字符串\n",
164 | "# apostrophe.py\n",
165 | "\n",
166 | "\n",
167 | "# 字符串单引号双引号的正确使用\n",
168 | "message = \"One of Python's strengths is its diverse community.\"\n",
169 | "print(message)"
170 | ]
171 | },
172 | {
173 | "cell_type": "markdown",
174 | "metadata": {},
175 | "source": [
176 | "## 2.3 数字"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {},
182 | "source": [
183 | "### 小结:\n",
184 | "\n",
185 | "#### py3的float不能精确显示(见最后一个0.1 + 0.2=0.30000000000000004)\n",
186 | "#### 整数相除,结果为float类型(Python2的整数相除为int型,同其他语言)\n",
187 | "#### 两个星号 * :乘方,相当于^\n",
188 | "#### 用+号连接str和int时,将int转为str:当int x, str(x)后在加号连接"
189 | ]
190 | },
191 | {
192 | "cell_type": "code",
193 | "execution_count": 34,
194 | "metadata": {
195 | "scrolled": true
196 | },
197 | "outputs": [
198 | {
199 | "name": "stdout",
200 | "output_type": "stream",
201 | "text": [
202 | "0.3333333333333333\n",
203 | "9\n",
204 | "1000000\n",
205 | "0.2\n",
206 | "0.30000000000000004\n"
207 | ]
208 | }
209 | ],
210 | "source": [
211 | "# 整数:加减乘除,乘方-两个乘号\n",
212 | "\n",
213 | "print(1/3) \n",
214 | " # 注意:python中整数除法与其他语言不同,不是强制砍掉小数部分\n",
215 | " # 注意:python2中,整数除法的规则与其他语言一致,直接砍掉小数部分(不四舍五入),故需至少一个操作数为浮点数\n",
216 | "\n",
217 | "print(3 ** 2)\n",
218 | "print(10 ** 6)\n",
219 | "\n",
220 | "# 浮点数:没什么特别的,注意小数位数可能是不确定的\n",
221 | "print(0.1 + 0.1)\n",
222 | "print(0.1 + 0.2)"
223 | ]
224 | },
225 | {
226 | "cell_type": "code",
227 | "execution_count": 36,
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "name": "stdout",
232 | "output_type": "stream",
233 | "text": [
234 | "Happy 23rd Birthday!\n"
235 | ]
236 | }
237 | ],
238 | "source": [
239 | "# 使用函数str()避免类型错误\n",
240 | "# birthday.py\n",
241 | "\n",
242 | "age = 23\n",
243 | "message = 'Happy ' + str(age) + 'rd Birthday!'\n",
244 | "print(message)"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "metadata": {},
250 | "source": [
251 | "## 2.4 注释\n",
252 | "\n",
253 | "### 小结:\n",
254 | "#### 单行:井号开头\n",
255 | "#### 多行:三个单引号或双引号分别在段首尾,为了好看最好另起一行(多行好像是文档注释,会生成什么文件吗...)"
256 | ]
257 | },
258 | {
259 | "cell_type": "code",
260 | "execution_count": 98,
261 | "metadata": {},
262 | "outputs": [
263 | {
264 | "name": "stdout",
265 | "output_type": "stream",
266 | "text": [
267 | "Hello Python People!\n"
268 | ]
269 | }
270 | ],
271 | "source": [
272 | "# comment.py\n",
273 | "# 向大家问好\n",
274 | "\n",
275 | "'''\n",
276 | "这里是:\n",
277 | "多行注释\n",
278 | "\n",
279 | "'''\n",
280 | "print('Hello Python People!')"
281 | ]
282 | },
283 | {
284 | "cell_type": "markdown",
285 | "metadata": {},
286 | "source": [
287 | "## 2.5 python之禅\n",
288 | "### 键入 import this 会显示"
289 | ]
290 | },
291 | {
292 | "cell_type": "markdown",
293 | "metadata": {},
294 | "source": [
295 | "* 美胜于丑。\n",
296 | "* 显式优于隐式。\n",
297 | "* 简单胜于复杂。\n",
298 | "* 复杂总比复杂好。\n",
299 | "* 平的比嵌套的好。\n",
300 | "* 稀疏胜于稠密。\n",
301 | "* 可读性计数。\n",
302 | "* 特殊情况不足以打破规则。\n",
303 | "* 尽管实用性胜过纯洁性。\n",
304 | "* 错误永远不会悄悄地过去。\n",
305 | "* 除非明确沉默。\n",
306 | "* 面对歧义,拒绝猜测的诱惑。\n",
307 | "* 应该有一种——最好只有一种——显而易见的方法来做到这一点。\n",
308 | "* 不过,如果不是荷兰语的话,这种方式一开始可能并不明显。\n",
309 | "* 现在总比没有好。\n",
310 | "* 虽然从来没有比现在更好。\n",
311 | "* 如果实现很难解释,那是个坏主意。\n",
312 | "* 如果实现很容易解释,这可能是一个好主意。\n",
313 | "* 名称空间是一个非常好的主意——让我们做更多的事情吧!"
314 | ]
315 | },
316 | {
317 | "cell_type": "code",
318 | "execution_count": 38,
319 | "metadata": {
320 | "scrolled": true
321 | },
322 | "outputs": [
323 | {
324 | "name": "stdout",
325 | "output_type": "stream",
326 | "text": [
327 | "The Zen of Python, by Tim Peters\n",
328 | "\n",
329 | "Beautiful is better than ugly.\n",
330 | "Explicit is better than implicit.\n",
331 | "Simple is better than complex.\n",
332 | "Complex is better than complicated.\n",
333 | "Flat is better than nested.\n",
334 | "Sparse is better than dense.\n",
335 | "Readability counts.\n",
336 | "Special cases aren't special enough to break the rules.\n",
337 | "Although practicality beats purity.\n",
338 | "Errors should never pass silently.\n",
339 | "Unless explicitly silenced.\n",
340 | "In the face of ambiguity, refuse the temptation to guess.\n",
341 | "There should be one-- and preferably only one --obvious way to do it.\n",
342 | "Although that way may not be obvious at first unless you're Dutch.\n",
343 | "Now is better than never.\n",
344 | "Although never is often better than *right* now.\n",
345 | "If the implementation is hard to explain, it's a bad idea.\n",
346 | "If the implementation is easy to explain, it may be a good idea.\n",
347 | "Namespaces are one honking great idea -- let's do more of those!\n"
348 | ]
349 | }
350 | ],
351 | "source": [
352 | "import this"
353 | ]
354 | }
355 | ],
356 | "metadata": {
357 | "kernelspec": {
358 | "display_name": "Python 3",
359 | "language": "python",
360 | "name": "python3"
361 | },
362 | "language_info": {
363 | "codemirror_mode": {
364 | "name": "ipython",
365 | "version": 3
366 | },
367 | "file_extension": ".py",
368 | "mimetype": "text/x-python",
369 | "name": "python",
370 | "nbconvert_exporter": "python",
371 | "pygments_lexer": "ipython3",
372 | "version": "3.7.0"
373 | }
374 | },
375 | "nbformat": 4,
376 | "nbformat_minor": 2
377 | }
378 |
--------------------------------------------------------------------------------
/src/PartI_Basics/03-列表简介.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第三章 列表简介\n",
8 | "\n",
9 | "知识点:列表的认识、创建、访问单个元素、修改、添加、删除、字母表排序、反转排序、求列表长度、索引注意事项"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "## 3.1 认识列表\n",
17 | "\n",
18 | "### 用方括号([ ] )来表示列表,并用逗号来分隔其中的元素,print时包括方括号、引号、逗号等\n",
19 | "### 由一系列按特定顺序排列的元素组成; 可以将任何东西加入列表中"
20 | ]
21 | },
22 | {
23 | "cell_type": "markdown",
24 | "metadata": {},
25 | "source": [
26 | "### 小结:\n",
27 | "\n",
28 | "#### 列表的格式:listname = [ , , , , ] --- 方括号,逗号隔开\n",
29 | "#### 列表的访问:listname[n] -- 按索引n访问列表\n",
30 | "#### 索引从0开始(同数组),负数表示倒数第几个"
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": 48,
36 | "metadata": {},
37 | "outputs": [
38 | {
39 | "name": "stdout",
40 | "output_type": "stream",
41 | "text": [
42 | "['trek', 'cannondale', 'redline', 'specialized']\n",
43 | "trek\n",
44 | "specialized\n",
45 | "My first bicycles was a Trek.\n"
46 | ]
47 | }
48 | ],
49 | "source": [
50 | "# 列表\n",
51 | "# bicycles.py\n",
52 | "\n",
53 | "bicycles = ['trek','cannondale','redline','specialized']\n",
54 | "print(bicycles)\n",
55 | "\n",
56 | "\n",
57 | "\n",
58 | "# 访问列表\n",
59 | "print(bicycles[0]) # 访问该列表的第一个元素\n",
60 | " # 当你请求获取列表元素时,Python只返回该元素,而不包括方括号和引号\n",
61 | "\n",
62 | "\n",
63 | "\n",
64 | "# 索引:从0开始;[]中负数表示末尾第几个元素\n",
65 | "print(bicycles[-1])\n",
66 | "\n",
67 | "\n",
68 | "\n",
69 | "# 使用列表中的各个值\n",
70 | "# 例如,可以使用拼接创建消息\n",
71 | "message = 'My first bicycles was a ' + bicycles[0].title() + '.'\n",
72 | "print(message)"
73 | ]
74 | },
75 | {
76 | "cell_type": "markdown",
77 | "metadata": {},
78 | "source": [
79 | "## 3.2 修改、添加、删除元素"
80 | ]
81 | },
82 | {
83 | "cell_type": "markdown",
84 | "metadata": {},
85 | "source": [
86 | "### 小结:\n",
87 | "\n",
88 | "#### 修改:listname[n] = '新' -- 将索引n对应的元素换位'新'\n",
89 | "#### 添加:listname.append('新') -- 将'新'添加到list的末尾\n",
90 | "#### 添加应用:动态地创建列表 -- 先创建空列表,然后一系列append添加 -- listname=[] listname.append('新')\n",
91 | "#### 插入:listname.insert(n, '新') -- 在listname的索引n处插入新元素'新'\n",
92 | "#### 删除:del语句;pop()方法;remove()方法 \n",
93 | "#### pop有返回值,remove没有返回值\n",
94 | "\n",
95 | "#### del listname[n]:知道要删除的元素在列表中的位置时使用。删除后无法再访问它。\n",
96 | "#### a = listname.pop():类似弹栈,弹出最后一个,并且返回该元素的值;弹出后仍能使用或访问这个值\n",
97 | "#### a = listname.pop(n):弹出索引n对应的元素;弹出后仍能使用\n",
98 | "#### listname.remove('列表中某元素'):只知道要删除元素的值,不知道索引时;移除列表中某个值的第一个匹配项;没有返回值"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 1,
104 | "metadata": {},
105 | "outputs": [
106 | {
107 | "name": "stdout",
108 | "output_type": "stream",
109 | "text": [
110 | "原列表motorcycles:\n",
111 | "['honda', 'yamaha', 'suzuki']\n",
112 | "\n",
113 | "修改:\n",
114 | "['ducati', 'yamaha', 'suzuki']\n",
115 | "\n",
116 | "添加1:末尾添加honda\n",
117 | "['ducati', 'yamaha', 'suzuki', 'honda']\n",
118 | "\n",
119 | "新列表motor:\n",
120 | "['honda', 'yamaha', 'suzuki']\n",
121 | "\n",
122 | "添加2:中间插入changhong\n",
123 | "['ducati', 'yamaha', 'changhong', 'suzuki', 'honda']\n",
124 | "\n",
125 | "删除1:del第一个元素ducati\n",
126 | "['yamaha', 'changhong', 'suzuki', 'honda']\n",
127 | "\n",
128 | "The last motorcycle I owned was a Honda.\n",
129 | "删除2:pop最后一个元素honda\n",
130 | "['yamaha', 'changhong', 'suzuki']\n",
131 | "\n",
132 | "The first motorcycles I owned was a Yamaha.\n",
133 | "删除3:pop指定位置元素[0]的yamaha\n",
134 | "['changhong', 'suzuki']\n",
135 | "\n",
136 | "删除4:remove删除指定的元素值suzuki\n",
137 | "['changhong']\n",
138 | "\n",
139 | "A Suzuki is too expensive for me.\n",
140 | "None\n"
141 | ]
142 | }
143 | ],
144 | "source": [
145 | "# motorcycles.py\n",
146 | "motorcycles = ['honda','yamaha','suzuki']\n",
147 | "print('原列表motorcycles:')\n",
148 | "print(motorcycles)\n",
149 | "\n",
150 | "\n",
151 | "# 修改:\n",
152 | "# 指定列表名和要修改的元素的索引,再指定该元素的新值\n",
153 | "motorcycles[0] = 'ducati'\n",
154 | "print('\\n修改:')\n",
155 | "print(motorcycles)\n",
156 | "\n",
157 | "\n",
158 | "\n",
159 | "# 添加:\n",
160 | "# 使用方法:末尾-append('新元素');中间-insert(索引,'新元素')\n",
161 | "# 1-末尾添加新元素:append()\n",
162 | "motorcycles.append('honda')\n",
163 | "print('\\n添加1:末尾添加honda')\n",
164 | "print(motorcycles)\n",
165 | "\n",
166 | "# 使用这个方法可以让动态地创建列表易如反掌,先创建一个空列表,再使用一系列append()。\n",
167 | "# 因为通常是程序运行后,才知道要存储哪些数据\n",
168 | "motor = []\n",
169 | "motor.append('honda')\n",
170 | "motor.append('yamaha')\n",
171 | "motor.append('suzuki')\n",
172 | "print('\\n新列表motor:')\n",
173 | "print(motor)\n",
174 | "\n",
175 | "# 2-中间插入新元素:insert()\n",
176 | "motorcycles.insert(2,'changhong')\n",
177 | "print('\\n添加2:中间插入changhong')\n",
178 | "print(motorcycles)\n",
179 | "\n",
180 | "\n",
181 | "\n",
182 | "# 删除:\n",
183 | "# del语句;pop()方法;remove()方法\n",
184 | "# del后元素值不可再用,pop和remove之后依然可以用值。(存疑:是不是remove也不行?见最后一个print测试)\n",
185 | "# 是不是语句不可赋值给变量,而方法可以??\n",
186 | "\n",
187 | "# 1-del语句:知道要删除的元素在列表中的位置时使用。删除后无法再访问它。\n",
188 | "del motorcycles[0]\n",
189 | "print('\\n删除1:del第一个元素ducati')\n",
190 | "print(motorcycles)\n",
191 | "\n",
192 | "# 2-pop()方法-弹出:弹出后仍然能使用(或访问)该值\n",
193 | "last_owned = motorcycles.pop() # 类似于弹栈 - 弹出最后的,即按时间线来说最后购买的那一款摩托车\n",
194 | "print('\\nThe last motorcycle I owned was a '+last_owned.title()+'.')\n",
195 | "print('删除2:pop最后一个元素honda')\n",
196 | "print(motorcycles)\n",
197 | "\n",
198 | "# 3-pop(索引)-删除任意位置的元素,在括号中指定要删除的元素的索引即可。\n",
199 | "first_owned = motorcycles.pop(0)\n",
200 | "print('\\nThe first motorcycles I owned was a ' + first_owned.title() + '.')\n",
201 | "print('删除3:pop指定位置元素[0]的yamaha')\n",
202 | "print(motorcycles)\n",
203 | "\n",
204 | "# 4-remove()-只知道要删除元素的值,不知道元素所处的位置时,删除后依然可以用\n",
205 | "# 方法remove() - 移除列表中某个值的第一个匹配项。\n",
206 | "# 如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。你将在第7章学习如何这样做。\n",
207 | "# 该方法没有返回值(见最后一句测试。说明移除后仍可用是个伪命题)\n",
208 | "too_expensive = 'suzuki' \n",
209 | "a = motorcycles.remove(too_expensive) # 事实上因为remove没有返回值,所以赋值给a没有作用。不必赋值给a\n",
210 | "print('\\n删除4:remove删除指定的元素值suzuki')\n",
211 | "print(motorcycles)\n",
212 | "print('\\nA '+too_expensive.title()+' is too expensive for me.')\n",
213 | "print(a) # 返回none啊.."
214 | ]
215 | },
216 | {
217 | "cell_type": "markdown",
218 | "metadata": {},
219 | "source": [
220 | "## 3.3 组织列表\n",
221 | "\n",
222 | "### 各种方式的排序"
223 | ]
224 | },
225 | {
226 | "cell_type": "markdown",
227 | "metadata": {},
228 | "source": [
229 | "### 小结:\n",
230 | "\n",
231 | "#### 不同方式的排序:sort(); sorted(); reverse()\n",
232 | "#### listname.sort():永久性排序,字母表顺序,a前z后,大写前小写后\n",
233 | "#### listname.sort(reverse = True):永久性排序,字母表逆序\n",
234 | "#### sorted(listname):临时性排序,字母表顺序,可赋值给变量后使用\n",
235 | "#### sorted(listname, reverse = True):临时性排序,字母表逆序\n",
236 | "#### listname.reverse():永久性修改,但随时可以恢复;倒着打印,注意是反转列表顺序,与字母表顺序无关\n",
237 | "#### len(listname):返回列表长度,可赋值给变量后使用"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": 5,
243 | "metadata": {
244 | "scrolled": false
245 | },
246 | "outputs": [
247 | {
248 | "name": "stdout",
249 | "output_type": "stream",
250 | "text": [
251 | "按字母表顺序排序:\n",
252 | "['audi', 'bmw', 'subaru', 'toyota']\n",
253 | "\n",
254 | "按字母表逆序排序:\n",
255 | "['toyota', 'subaru', 'bmw', 'audi']\n",
256 | "\n",
257 | "Here is the original list:\n",
258 | "['bmw', 'audi', 'toyota', 'subaru']\n",
259 | "\n",
260 | "Here is the sorted list:\n",
261 | "['audi', 'bmw', 'subaru', 'toyota']\n",
262 | "['audi', 'bmw', 'subaru', 'toyota']\n",
263 | "\n",
264 | "Here is the reverse alphabetical list:\n",
265 | "['toyota', 'subaru', 'bmw', 'audi']\n",
266 | "\n",
267 | "Here is the original list again:\n",
268 | "['bmw', 'audi', 'toyota', 'subaru']\n",
269 | "\n",
270 | "倒着打印列表演示:\n",
271 | "['bmw', 'audi', 'toyota', 'subaru']\n",
272 | "['subaru', 'toyota', 'audi', 'bmw']\n",
273 | "\n",
274 | "输出列表长度:\n",
275 | "4\n",
276 | "4\n"
277 | ]
278 | }
279 | ],
280 | "source": [
281 | "# 1-sort()-永久性;2-sorted()-临时性;\n",
282 | "# cars.py\n",
283 | "\n",
284 | "# sort()-对列表永久性排序(假设所有值都是小写;大小写混合时大写在前)\n",
285 | "cars = ['bmw','audi','toyota','subaru']\n",
286 | "print('按字母表顺序排序:')\n",
287 | "cars.sort()\n",
288 | "print(cars)\n",
289 | "\n",
290 | "# sort(reverse=True)-按字母表逆序排序,永久性\n",
291 | "print('\\n按字母表逆序排序:')\n",
292 | "cars.sort(reverse=True)\n",
293 | "print(cars)\n",
294 | "\n",
295 | "\n",
296 | "\n",
297 | "# sorted()-对列表进行临时排序\n",
298 | "cars = ['bmw','audi','toyota','subaru']\n",
299 | "print('\\nHere is the original list:')\n",
300 | "print(cars)\n",
301 | "\n",
302 | "print('\\nHere is the sorted list:')\n",
303 | "print(sorted(cars))\n",
304 | "abc = sorted(cars)\n",
305 | "print(abc)\n",
306 | "\n",
307 | "print('\\nHere is the reverse alphabetical list:')\n",
308 | "print(sorted(cars,reverse=True)) # 注意这一条:用sorted逆序排序的正确格式\n",
309 | "\n",
310 | "print('\\nHere is the original list again:')\n",
311 | "print(cars)\n",
312 | "\n",
313 | "\n",
314 | "\n",
315 | "# reverse()-倒着打印列表,永久性修改,但随时可以恢复到原来的排序\n",
316 | "# 注意:不是按与字母顺序相反的顺序,而是反转列表元素的顺序排列\n",
317 | "carss = ['bmw','audi','toyota','subaru']\n",
318 | "print('\\n倒着打印列表演示:')\n",
319 | "print(carss)\n",
320 | "\n",
321 | "carss.reverse()\n",
322 | "print(carss)\n",
323 | "\n",
324 | "\n",
325 | "\n",
326 | "# len()-列表长度\n",
327 | "print('\\n输出列表长度:')\n",
328 | "print(len(carss))\n",
329 | "acda = len(carss)\n",
330 | "print(acda)"
331 | ]
332 | },
333 | {
334 | "cell_type": "markdown",
335 | "metadata": {},
336 | "source": [
337 | "## 3.4 使用列表索引时避免错误\n",
338 | "\n",
339 | "#### 1 - 索引从0开始\n",
340 | "#### 2 - ‘-1’在任何时候都可以用来指向最后一个元素,除非列表为空才报错\n",
341 | "#### 3 - 发生索引错误却找不到解决方法时,可将列表或其长度打印出来,可以与自己以为的截然不同。"
342 | ]
343 | }
344 | ],
345 | "metadata": {
346 | "kernelspec": {
347 | "display_name": "Python 3",
348 | "language": "python",
349 | "name": "python3"
350 | },
351 | "language_info": {
352 | "codemirror_mode": {
353 | "name": "ipython",
354 | "version": 3
355 | },
356 | "file_extension": ".py",
357 | "mimetype": "text/x-python",
358 | "name": "python",
359 | "nbconvert_exporter": "python",
360 | "pygments_lexer": "ipython3",
361 | "version": "3.7.0"
362 | }
363 | },
364 | "nbformat": 4,
365 | "nbformat_minor": 2
366 | }
367 |
--------------------------------------------------------------------------------
/src/PartI_Basics/04-操作列表.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第四章 操作列表\n",
8 | "\n",
9 | "知识点:for循环、缩进注意点、数值列表创建、数学统计(最值、求和)、列表解析、列表切片、元组、代码格式优化"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "## 4.1 遍历整个列表\n",
17 | "\n",
18 | "### for循环遍历\n",
19 | "\n",
20 | "#### 刚开始使用循环时请牢记,对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。\n",
21 | "\n",
22 | "#### 如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次,且通常速度非常快。"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "### 小结:\n",
30 | "\n",
31 | "#### 格式:for n-任意名字 in listname: 某语句"
32 | ]
33 | },
34 | {
35 | "cell_type": "code",
36 | "execution_count": 80,
37 | "metadata": {},
38 | "outputs": [
39 | {
40 | "name": "stdout",
41 | "output_type": "stream",
42 | "text": [
43 | "打印魔术师名单中所有名字:\n",
44 | "alice\n",
45 | "david\n",
46 | "carolina\n",
47 | "Alice,that was a great trick\n",
48 | "I can't wait to see your next trick,Alice.\n",
49 | "\n",
50 | "David,that was a great trick\n",
51 | "I can't wait to see your next trick,David.\n",
52 | "\n",
53 | "Carolina,that was a great trick\n",
54 | "I can't wait to see your next trick,Carolina.\n",
55 | "\n",
56 | "Thank you, everyone. That was a great magic show!\n"
57 | ]
58 | }
59 | ],
60 | "source": [
61 | "# 遍历列表 - 魔术师演示\n",
62 | "# magicians.py\n",
63 | "\n",
64 | "magicians = ['alice','david','carolina']\n",
65 | "print('打印魔术师名单中所有名字:')\n",
66 | "for magician in magicians:\n",
67 | " print(magician)\n",
68 | "for magician in magicians:\n",
69 | " print(magician.title() + ',that was a great trick')\n",
70 | " print(\"I can't wait to see your next trick,\" + magician.title() + '.\\n')\n",
71 | "print('Thank you, everyone. That was a great magic show!')"
72 | ]
73 | },
74 | {
75 | "cell_type": "markdown",
76 | "metadata": {},
77 | "source": [
78 | "## 4.2 避免缩进错误\n",
79 | "### Python根据缩进来判断代码行与前一个代码行的关系\n",
80 | "\n",
81 | "#### 1-忘记缩进\n",
82 | "#### 2-忘记缩进额外的代码行\n",
83 | "#### 3-不必要的缩进\n",
84 | "#### 4-循环后不必要的缩进\n",
85 | "#### 5-遗漏冒号(python有冒号,无分号,用缩进代替大括号,注意别混淆了)"
86 | ]
87 | },
88 | {
89 | "cell_type": "markdown",
90 | "metadata": {},
91 | "source": [
92 | "## 4.3 创建数值列表"
93 | ]
94 | },
95 | {
96 | "cell_type": "markdown",
97 | "metadata": {},
98 | "source": [
99 | "### 小结:\n",
100 | "\n",
101 | "#### range(start, stop, step):创建一个整数列表,一般用在 for 循环中\n",
102 | "#### range():默认从0开始,默认step为1,这两个都可以省略(step优先省略),stop必须有,不包括stop本值\n",
103 | "#### list(range(n)):将range()的结果直接转换为列表,可存储在变量中以后使用\n",
104 | "#### 用range()创建任意数据集:新建空列表--for循环-append\n",
105 | "#### 数学统计:min(listname)-最小值;max(listname)-最大值;sum(listname)-求和\n",
106 | "\n",
107 | "#### 列表解析:创建列表 - listname = [value计算或表达式 for value in range(n)]"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 82,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "name": "stdout",
117 | "output_type": "stream",
118 | "text": [
119 | "1\n",
120 | "2\n",
121 | "3\n",
122 | "4\n",
123 | "[1, 2, 3, 4, 5]\n"
124 | ]
125 | }
126 | ],
127 | "source": [
128 | "# number.py\n",
129 | "\n",
130 | "# range()函数 - range(a,b)生成从a到b且不包含b的一系列数值\n",
131 | "for value in range(1,5): #生成1-4\n",
132 | " print(value)\n",
133 | "\n",
134 | "# 使用range()创建数字列表\n",
135 | "# list()-将range()结果直接转换为列表\n",
136 | "numbers = list(range(1,6))\n",
137 | "print(numbers)"
138 | ]
139 | },
140 | {
141 | "cell_type": "code",
142 | "execution_count": 84,
143 | "metadata": {},
144 | "outputs": [
145 | {
146 | "name": "stdout",
147 | "output_type": "stream",
148 | "text": [
149 | "[2, 4, 6, 8, 10]\n"
150 | ]
151 | }
152 | ],
153 | "source": [
154 | "# even_numbers.py\n",
155 | "# 打印1-10以内的偶数\n",
156 | "# range()-第三个参数指定步长\n",
157 | "\n",
158 | "even_numbers = list(range(2,11,2))\n",
159 | "print(even_numbers)"
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "execution_count": 91,
165 | "metadata": {},
166 | "outputs": [
167 | {
168 | "name": "stdout",
169 | "output_type": "stream",
170 | "text": [
171 | "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n",
172 | "min=0\n",
173 | "max=9\n",
174 | "sum=45\n"
175 | ]
176 | }
177 | ],
178 | "source": [
179 | "# squares.py\n",
180 | "# 创建一个列表,包含前10个整数的平方\n",
181 | "# 万能的range()几乎能够创建任何需要的数字集\n",
182 | "\n",
183 | "# 思路:新建空列表(变量名=[])--遍历(for循环)--每个值取平方(**)--将每个结果添加到列表中(append)\n",
184 | "squares = []\n",
185 | "for value in range(1,11):\n",
186 | " square = value**2\n",
187 | " squares.append(square)\n",
188 | " # 以上两句可以合并: squares.append(value**2)\n",
189 | "\n",
190 | "print(squares)\n",
191 | "\n",
192 | "\n",
193 | "\n",
194 | "# 对数字列表执行简单的统计计算:max,min,sum\n",
195 | "digits = [1,2,3,4,5,6,7,8,9,0]\n",
196 | "print('min=%d' %min(digits))\n",
197 | "print('max=%d' %max(digits))\n",
198 | "print('sum=%d' %sum(digits))"
199 | ]
200 | },
201 | {
202 | "cell_type": "markdown",
203 | "metadata": {},
204 | "source": [
205 | "### 列表解析 \n",
206 | "\n",
207 | "#### 将for 循环和创建新元素的代码合并成一行,并自动附加新元素。\n",
208 | "#### 初学者不要求会写,但尽量看懂,因为可能在读别人的代码时会遇到"
209 | ]
210 | },
211 | {
212 | "cell_type": "code",
213 | "execution_count": 99,
214 | "metadata": {},
215 | "outputs": [
216 | {
217 | "name": "stdout",
218 | "output_type": "stream",
219 | "text": [
220 | "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n"
221 | ]
222 | }
223 | ],
224 | "source": [
225 | "# 使用列表解析创建前面的平方数列表\n",
226 | "\n",
227 | "\"\"\"\n",
228 | "语法:\n",
229 | "\n",
230 | "首先指定一个描述性的列表名,如squares ;\n",
231 | "\n",
232 | "然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。\n",
233 | "在这个示例中,表达式为value**2 ,它计算平方值。\n",
234 | "\n",
235 | "接下来,编写一个for 循环,用于给表达式提供值,再加上右方括号。\n",
236 | "在这个示例中,for 循环为for value in range(1,11) ,它将值1~10提供给表达式value**2 。\n",
237 | "\n",
238 | "请注意,这里的for 语句末尾没有冒号。\n",
239 | "\n",
240 | "\"\"\"\n",
241 | "# 以上这段注释如放在print语句之后,运行时会out注释里的内容,放在print前面之后就不会错误了\n",
242 | "\n",
243 | "squares = [value**2 for value in range(1,11)]\n",
244 | "print(squares)"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "metadata": {},
250 | "source": [
251 | "## 4.4 使用列表的一部分"
252 | ]
253 | },
254 | {
255 | "cell_type": "markdown",
256 | "metadata": {},
257 | "source": [
258 | "### 小结:\n",
259 | "\n",
260 | "#### 切片:m n -- 索引值\n",
261 | "#### listname[m:n] -- 从索引值m处取到索引n的前一个元素(第m-1个到第n个)\n",
262 | "#### listname[:n] -- 没有指定m时,默认从列表第一个元素开始\n",
263 | "#### listname[m:] -- 没有指定n时,默认取到列表的最后一个元素\n",
264 | "#### listname[-m:] -- m或n为负数时,从倒数第三位取到最后一个元素 \n",
265 | "#### listname[:] -- 取所有元素(是全新副本不是关联,相当于复制但区别于copy deepcopy等等,后两个的规则不太懂。。)"
266 | ]
267 | },
268 | {
269 | "cell_type": "code",
270 | "execution_count": 103,
271 | "metadata": {
272 | "scrolled": true
273 | },
274 | "outputs": [
275 | {
276 | "name": "stdout",
277 | "output_type": "stream",
278 | "text": [
279 | "['charles', 'martina', 'michael']\n",
280 | "['charles', 'martina', 'michael']\n",
281 | "['michael', 'florence', 'eli']\n",
282 | "['michael', 'florence', 'eli']\n",
283 | "\n",
284 | "Here are the first three players on my team:\n",
285 | "Charles\n",
286 | "Martina\n",
287 | "Michael\n"
288 | ]
289 | }
290 | ],
291 | "source": [
292 | "# players.py\n",
293 | "# 对运动员名单列表切片\n",
294 | "\n",
295 | "players = ['charles','martina','michael','florence','eli']\n",
296 | "\n",
297 | "# 冒号连接想要取得的第一个和最后一个索引的后一个索引\n",
298 | "print(players[0:3]) # 第一个到第三个\n",
299 | "print(players[:3]) # 没有指定第一个索引时从列表开头开始\n",
300 | "print(players[2:]) # 没有指定最后一个索引时一直执行到列表末尾\n",
301 | "print(players[-3:]) # 从倒数第三位开始执行到列表末尾\n",
302 | "\n",
303 | "\n",
304 | "\n",
305 | "# 遍历切片:for循环+[:]切片\n",
306 | "print('\\nHere are the first three players on my team:')\n",
307 | "for player in players[:3]:\n",
308 | " print(player.title())"
309 | ]
310 | },
311 | {
312 | "cell_type": "code",
313 | "execution_count": 109,
314 | "metadata": {},
315 | "outputs": [
316 | {
317 | "name": "stdout",
318 | "output_type": "stream",
319 | "text": [
320 | "My favortie foods are:\n",
321 | "['pizza', 'falafel', 'carrot cake', 'ice cream']\n",
322 | "\n",
323 | "My friend's favorite foods are:\n",
324 | "['pizza', 'falafel', 'carrot cake', 'cannoli']\n"
325 | ]
326 | }
327 | ],
328 | "source": [
329 | "# foods.py\n",
330 | "# 复制列表:把切片赋值给新的变量,而不是直接把变量赋给(相当于关联而不是把副本存储到新变量中)\n",
331 | "\n",
332 | "# friend_foods = my_foods 这样的话只是新变量关联到包含my_foods中的列表,如果原变量变化,新变量也跟着变化\n",
333 | "\n",
334 | "# 我喜欢的食物,我朋友也喜欢\n",
335 | "my_foods = ['pizza','falafel','carrot cake']\n",
336 | "friend_foods = my_foods[:]\n",
337 | "\n",
338 | "my_foods.append('ice cream')\n",
339 | "friend_foods.append('cannoli')\n",
340 | "\n",
341 | "print('My favortie foods are:')\n",
342 | "print(my_foods)\n",
343 | "\n",
344 | "print(\"\\nMy friend's favorite foods are:\")\n",
345 | "print(friend_foods)\n"
346 | ]
347 | },
348 | {
349 | "cell_type": "markdown",
350 | "metadata": {},
351 | "source": [
352 | "## 4.5 元组\n",
353 | "\n",
354 | "#### 列表 - 适合存储可能变化的数据集,使用方括号标识(考点:列表不可作为字典的key,键要求唯一、不可变)\n",
355 | "#### 元组 - 不可变的列表称为元组,使用圆括号标识\n",
356 | "\n",
357 | "### 相比列表,元组是更简单的数据结构。如需存储的一组值在程序的整个生命周期内都不变,可使用元组"
358 | ]
359 | },
360 | {
361 | "cell_type": "markdown",
362 | "metadata": {},
363 | "source": [
364 | "### 小结:\n",
365 | "\n",
366 | "#### tuplename = ( , , , )\n",
367 | "#### 不可以修改元组的值:tuplename[n] = m -- 会报错\n",
368 | "#### 虽然不可以修改元组,但是可以对存储元组的变量重新赋值(这也算吗...)"
369 | ]
370 | },
371 | {
372 | "cell_type": "code",
373 | "execution_count": 114,
374 | "metadata": {},
375 | "outputs": [
376 | {
377 | "name": "stdout",
378 | "output_type": "stream",
379 | "text": [
380 | "200\n",
381 | "50\n",
382 | "\n",
383 | "Original dimensions:\n",
384 | "200\n",
385 | "50\n",
386 | "\n",
387 | "Modified dimensions:\n",
388 | "400\n",
389 | "100\n"
390 | ]
391 | }
392 | ],
393 | "source": [
394 | "# dimensions.py\n",
395 | "# 定义一个大小不变的矩形,将其长度和宽度存储在一个元组中,从而确保它们是不能修改\n",
396 | "\n",
397 | "dimensions = (200,50)\n",
398 | "print(dimensions[0])\n",
399 | "print(dimensions[1])\n",
400 | "\n",
401 | "# 尝试修改元组的元素值\n",
402 | "# dimensions[0]=300\n",
403 | "# TypeError: 'tuple' object does not support item assignment 修改元组的操作是被禁止的\n",
404 | "\n",
405 | "\n",
406 | "\n",
407 | "# 遍历元组中的所有值\n",
408 | "print('\\nOriginal dimensions:')\n",
409 | "for dimension in dimensions:\n",
410 | " print(dimension)\n",
411 | " \n",
412 | " \n",
413 | " \n",
414 | "# 修改元组的变量\n",
415 | "# 虽然不能修改元组的元素,但是可以给存储元组的变量赋值,即可以重新定义整个元组。给元组变量赋值是合法的。\n",
416 | "dimensions = (400,100)\n",
417 | "print('\\nModified dimensions:')\n",
418 | "for dimension in dimensions:\n",
419 | " print(dimension)"
420 | ]
421 | },
422 | {
423 | "cell_type": "markdown",
424 | "metadata": {},
425 | "source": [
426 | "## 4.6 设置代码格式"
427 | ]
428 | },
429 | {
430 | "cell_type": "markdown",
431 | "metadata": {},
432 | "source": [
433 | "### 格式设置指南:Python改进提案 (Python Enhancement Proposal,PEP)\n",
434 | "\n",
435 | "#### 缩进:4个空格为一级缩进\n",
436 | "\n",
437 | "#### 行长:建议每行不超过80字符\n",
438 | "\n",
439 | "#### 空行:python解释器不关心但影响可读性,尽量合理\n",
440 | "\n",
441 | "#### 其他"
442 | ]
443 | }
444 | ],
445 | "metadata": {
446 | "kernelspec": {
447 | "display_name": "Python 3",
448 | "language": "python",
449 | "name": "python3"
450 | },
451 | "language_info": {
452 | "codemirror_mode": {
453 | "name": "ipython",
454 | "version": 3
455 | },
456 | "file_extension": ".py",
457 | "mimetype": "text/x-python",
458 | "name": "python",
459 | "nbconvert_exporter": "python",
460 | "pygments_lexer": "ipython3",
461 | "version": "3.7.0"
462 | }
463 | },
464 | "nbformat": 4,
465 | "nbformat_minor": 2
466 | }
467 |
--------------------------------------------------------------------------------
/src/PartI_Basics/05-if语句.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第五章 if语句\n",
8 | "\n",
9 | "知识点:if语句,if-else,if-elif,多个if,各种if嵌套,条件测试(布尔表达式),比较数值大小,多个条件(and,or),检测特定值是/不包含在列表中/列表是否为空/一个列表是否在另一个列表中,if格式(空格增加可读性)"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "## 5.1 一个简单示例"
17 | ]
18 | },
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {},
22 | "source": [
23 | "### 小结:\n",
24 | "\n",
25 | "#### if语句格式:if xxx: xxx else: xxx"
26 | ]
27 | },
28 | {
29 | "cell_type": "code",
30 | "execution_count": 115,
31 | "metadata": {},
32 | "outputs": [
33 | {
34 | "name": "stdout",
35 | "output_type": "stream",
36 | "text": [
37 | "Audi\n",
38 | "BMW\n",
39 | "Subaru\n",
40 | "Toyota\n"
41 | ]
42 | }
43 | ],
44 | "source": [
45 | "# cars.py\n",
46 | "cars = ['audi','bmw','subaru','toyota']\n",
47 | "\n",
48 | "for car in cars:\n",
49 | " if car == 'bmw':\n",
50 | " print(car.upper())\n",
51 | " else:\n",
52 | " print(car.title())"
53 | ]
54 | },
55 | {
56 | "cell_type": "markdown",
57 | "metadata": {},
58 | "source": [
59 | "## 5.2 条件测试(布尔表达式)\n",
60 | "\n",
61 | "### 每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试"
62 | ]
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {},
67 | "source": [
68 | "### 小结:\n",
69 | "\n",
70 | "#### if 条件测试(布尔表达式,就是一个为True 或者 False的表达式)\n",
71 | "#### 数值大小比较:正常比较,如> >= < <=\n",
72 | "#### 检查多个条件:and 或者 or组合,符合数学中的“与”和“或”的规则\n",
73 | "#### 检查特定值是否包含在列表中: 'x' in list_name - 结果:True or False\n",
74 | "#### 检查特定值是否不包含在列表中:关键字 not in - 'x' not in list_name - 结果:True or False,不包含时返回True"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": 124,
80 | "metadata": {},
81 | "outputs": [
82 | {
83 | "name": "stdout",
84 | "output_type": "stream",
85 | "text": [
86 | "True\n",
87 | "False\n",
88 | "True\n"
89 | ]
90 | }
91 | ],
92 | "source": [
93 | "# 1-检查是否相等\n",
94 | "# 先赋值,后判断是否为某个值\n",
95 | "car = 'Audi'\n",
96 | "print(car == 'Audi')\n",
97 | "\n",
98 | "\n",
99 | "\n",
100 | "# 2-检查是否相等时考虑大小写\n",
101 | "print(car == 'audi')\n",
102 | "\n",
103 | "# 如果大小写很重要,这种行为有其优点。如果大小写不重要,只想检查变量的值,可将变量值转换为小写再比较\n",
104 | "# lower()不会修改存储在变量car中的值,因此这样比较时不会影响原来的变量\n",
105 | "# 例子:网站注册用户名时,确保无论大小写都是独一无二的才可以通过\n",
106 | "print(car.lower() == 'audi')"
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": 125,
112 | "metadata": {},
113 | "outputs": [
114 | {
115 | "name": "stdout",
116 | "output_type": "stream",
117 | "text": [
118 | "Hold the anchovies!\n"
119 | ]
120 | }
121 | ],
122 | "source": [
123 | "# toppings.py\n",
124 | "# 把要求的披萨配料存储在一个变量中,顾客要求的配料是否是意式小银鱼(anchovies)\n",
125 | "\n",
126 | "# 3-检查是否不相等\n",
127 | "requested_topping = 'mushrooms'\n",
128 | "if requested_topping != 'anchovies':\n",
129 | " print('Hold the anchovies!')"
130 | ]
131 | },
132 | {
133 | "cell_type": "code",
134 | "execution_count": 134,
135 | "metadata": {},
136 | "outputs": [
137 | {
138 | "name": "stdout",
139 | "output_type": "stream",
140 | "text": [
141 | "True\n",
142 | "That is not the correct answer. Please try again!\n",
143 | "False\n",
144 | "False\n",
145 | "False\n",
146 | "True\n",
147 | "False\n"
148 | ]
149 | }
150 | ],
151 | "source": [
152 | "# 4-比较数字\n",
153 | "# 检查一个人是否是18岁:\n",
154 | "age = 18\n",
155 | "print(age == 18)\n",
156 | "\n",
157 | "# magic_number.py\n",
158 | "# 检查两个数字是否不等\n",
159 | "answer = 17\n",
160 | "if answer != 42:\n",
161 | " print('That is not the correct answer. Please try again!')\n",
162 | "\n",
163 | " \n",
164 | " \n",
165 | "# 在if 语句中可使用各种数学比较,这让你能够直接检查关心的条件\n",
166 | "# 条件语句中可包含各种数学比较,如> >= < <=\n",
167 | "print(age == 19)\n",
168 | "print(age > 21)\n",
169 | "print(age <= 13)\n",
170 | "\n",
171 | "\n",
172 | "\n",
173 | "# 5-检查多个条件:and 或者 or组合多个条件\n",
174 | "\n",
175 | "\n",
176 | "\n",
177 | "# 6-检查特定值是否包含在列表中: 'x' in list_name - True or False\n",
178 | "requested_toppings = ['mushroom','onions','pineapple']\n",
179 | "a = 'mushroom' in requested_toppings\n",
180 | "print(a)\n",
181 | "b = 'pepperoni' in requested_toppings\n",
182 | "print(b)"
183 | ]
184 | },
185 | {
186 | "cell_type": "code",
187 | "execution_count": 137,
188 | "metadata": {},
189 | "outputs": [
190 | {
191 | "name": "stdout",
192 | "output_type": "stream",
193 | "text": [
194 | "Marie,you can post a response if you wish.\n"
195 | ]
196 | }
197 | ],
198 | "source": [
199 | "# banned_user.py\n",
200 | "# 7-检查特定值是否不包含在列表中:关键字 not in - 不包含时返回True\n",
201 | "# 例如:如果有一个列表,其中包含被禁止在论坛发言的用户\n",
202 | "banned_users = ['andrew','carolina','david']\n",
203 | "user = 'marie'\n",
204 | "\n",
205 | "if user not in banned_users:\n",
206 | " print(user.title()+',you can post a response if you wish.')\n",
207 | "# 如果user在禁言名单,什么都不显示\n",
208 | "\n",
209 | "\n",
210 | "\n",
211 | "# 8-布尔表达式:条件测试的别名(反倒是我没听过条件测试哈哈)\n",
212 | "# 布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容\n",
213 | "game_active = True\n",
214 | "can_edit = False"
215 | ]
216 | },
217 | {
218 | "cell_type": "markdown",
219 | "metadata": {},
220 | "source": [
221 | "## 5.3 if语句"
222 | ]
223 | },
224 | {
225 | "cell_type": "markdown",
226 | "metadata": {},
227 | "source": [
228 | "### 小结:\n",
229 | "\n",
230 | "#### if-else结构\n",
231 | "#### if嵌套:if-elif-...-else结构\n",
232 | "#### 测试多个条件:if... if... if..."
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": 142,
238 | "metadata": {},
239 | "outputs": [
240 | {
241 | "name": "stdout",
242 | "output_type": "stream",
243 | "text": [
244 | "You are old enough to vote!\n",
245 | "Have you registered to vote yet?\n"
246 | ]
247 | }
248 | ],
249 | "source": [
250 | "# voting.py\n",
251 | "# if-else结构非常适用于执行两种操作之一的情形\n",
252 | "\n",
253 | "age = 19\n",
254 | "if age >= 18:\n",
255 | " print('You are old enough to vote!')\n",
256 | " print('Have you registered to vote yet?')\n",
257 | "else:\n",
258 | " print('Sorry, you are too young to vote.')\n",
259 | " print('Please register to vote as soon as you turn 18!')"
260 | ]
261 | },
262 | {
263 | "cell_type": "code",
264 | "execution_count": 146,
265 | "metadata": {},
266 | "outputs": [
267 | {
268 | "name": "stdout",
269 | "output_type": "stream",
270 | "text": [
271 | "Your admission cost is $5.\n"
272 | ]
273 | }
274 | ],
275 | "source": [
276 | "# amusement_park.py\n",
277 | "# if-elif-else结构适用于两个以上情形\n",
278 | "# 可根据需要使用任意数量的elif代码块,例如给老年人打折,可再添加一个条件测试\n",
279 | "\n",
280 | "age = 12\n",
281 | "if age < 4:\n",
282 | " price = 0\n",
283 | "elif age< 18:\n",
284 | " price = 5\n",
285 | "elif age < 65:\n",
286 | " price = 10\n",
287 | "else: # 或者elif age >= 65 \n",
288 | " # 省略else代码块,用elif来处理特定的情形更清晰\n",
289 | " # else:一条包罗万象的语句,可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用elif代替else\n",
290 | " price =10\n",
291 | "print('Your admission cost is $'+str(price)+'.') # 前面遇到过这种typeError,这里把整数类型转换成str"
292 | ]
293 | },
294 | {
295 | "cell_type": "code",
296 | "execution_count": 1,
297 | "metadata": {},
298 | "outputs": [
299 | {
300 | "name": "stdout",
301 | "output_type": "stream",
302 | "text": [
303 | "Adding mushrooms.\n",
304 | "Adding extra cheese.\n"
305 | ]
306 | }
307 | ],
308 | "source": [
309 | "# toppings.py\n",
310 | "# 测试多个条件\n",
311 | "\n",
312 | "# 披萨店示例:如果顾客点了两种配料,就需要确保在其披萨中包含这些配料\n",
313 | "requested_toppings = ['mushrooms','extra cheese']\n",
314 | "\n",
315 | "if 'mushrooms' in requested_toppings:\n",
316 | " print('Adding mushrooms.')\n",
317 | "if 'pepperoni' in requested_toppings:\n",
318 | " print('Adding pepperoni.')\n",
319 | "if 'extra cheese' in requested_toppings:\n",
320 | " print('Adding extra cheese.')\n",
321 | "\n",
322 | "# 这一条可能是要说明一个非常浅显的道理,就是如果用if-else,当符合前一个条件时,后面的统统不执行了,某些情形不适用。\n",
323 | "\n",
324 | "# 只想执行一个代码块,就使用if-elif-else结构;\n",
325 | "# 如果要运行多个代码块,就使用一系列独立的if语句"
326 | ]
327 | },
328 | {
329 | "cell_type": "markdown",
330 | "metadata": {},
331 | "source": [
332 | "\n",
333 | "## 5.4 使用if语句处理列表"
334 | ]
335 | },
336 | {
337 | "cell_type": "markdown",
338 | "metadata": {},
339 | "source": [
340 | "### 小结:\n",
341 | "\n",
342 | "#### 检查特殊元素:for a in listname: if a == 'sth' (如果b列表中包含sth,就怎样)\n",
343 | "#### 检查列表不是空的:if listname: ... \n",
344 | "#### 检查一个列表a是否在另一个列表b中:for a in a_list: if a in b_list: ..."
345 | ]
346 | },
347 | {
348 | "cell_type": "code",
349 | "execution_count": 4,
350 | "metadata": {},
351 | "outputs": [
352 | {
353 | "name": "stdout",
354 | "output_type": "stream",
355 | "text": [
356 | "Adding mushrooms.\n",
357 | "Sorry, we are out of green peppers right now.\n",
358 | "Adding extra cheese.\n",
359 | "\n",
360 | "Finished making your pizza!\n",
361 | "\n",
362 | "Are you sure you want a plain pizza?\n",
363 | "\n",
364 | "\n",
365 | "Adding mushrooms.\n",
366 | "Sorry, we dont have french fries.\n",
367 | "Adding extra cheese.\n",
368 | "\n",
369 | "Finished making your pizza!\n"
370 | ]
371 | }
372 | ],
373 | "source": [
374 | "# toppings.py\n",
375 | "# 披萨店示例 - 制作披萨时,用户的点单系统,每添加一种配料都打印一条消息。\n",
376 | "# 创建一个列表,在其中包含顾客点的配料,并使用一个循环来指出添加到披萨中的配料。\n",
377 | "\n",
378 | "\n",
379 | "# 检查特殊元素\n",
380 | "# 如果青椒用完了,就显示一条消息,指出不能点青椒的原因。\n",
381 | "requested_toppings = ['mushrooms','green peppers','extra cheese']\n",
382 | "\n",
383 | "for requested_topping in requested_toppings:\n",
384 | " if requested_topping == 'green peppers':\n",
385 | " print('Sorry, we are out of green peppers right now.')\n",
386 | " else:\n",
387 | " print('Adding ' + requested_topping+'.')\n",
388 | "\n",
389 | "print('\\nFinished making your pizza!')\n",
390 | "\n",
391 | "\n",
392 | "\n",
393 | "# 确定列表不是空的\n",
394 | "# Python将在列表至少包含一个元素时返回True\n",
395 | "requested_toppings = []\n",
396 | "\n",
397 | "if requested_toppings: # 列表为空,返回Flase,执行else的内容\n",
398 | " for requested_toppings in requested_toppings:\n",
399 | " print('\\nAdding '+requested_topping+'.')\n",
400 | " print('\\nFinished making your pizza!')\n",
401 | "else:\n",
402 | " print('\\nAre you sure you want a plain pizza?')\n",
403 | " print('\\n')\n",
404 | "\n",
405 | " \n",
406 | " \n",
407 | "# 使用多个列表\n",
408 | "# 第一个列表包含比萨店供应的配料,第二个包含顾客点的配料。\n",
409 | "# 对requested_toppings中的每个元素,都检查它是否是比萨店供应的配料,再决定是否在比萨中添加它。\n",
410 | "available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']\n",
411 | "requested_toppings = ['mushrooms','french fries','extra cheese']\n",
412 | "for requested_topping in requested_toppings:\n",
413 | " if requested_topping in available_toppings:\n",
414 | " print('Adding ' + requested_topping + '.')\n",
415 | " else:\n",
416 | " print('Sorry, we dont have ' + requested_topping + '.')\n",
417 | "\n",
418 | "print('\\nFinished making your pizza!')"
419 | ]
420 | },
421 | {
422 | "cell_type": "markdown",
423 | "metadata": {},
424 | "source": [
425 | "## 5.5 设置if语句的格式\n",
426 | "\n",
427 | "#### 在诸如== 、>= 和<= 等比较运算符两边各添加一个空格,例如,if age < 4: 要比if age<4: 好。"
428 | ]
429 | }
430 | ],
431 | "metadata": {
432 | "kernelspec": {
433 | "display_name": "Python 3",
434 | "language": "python",
435 | "name": "python3"
436 | },
437 | "language_info": {
438 | "codemirror_mode": {
439 | "name": "ipython",
440 | "version": 3
441 | },
442 | "file_extension": ".py",
443 | "mimetype": "text/x-python",
444 | "name": "python",
445 | "nbconvert_exporter": "python",
446 | "pygments_lexer": "ipython3",
447 | "version": "3.7.0"
448 | }
449 | },
450 | "nbformat": 4,
451 | "nbformat_minor": 2
452 | }
453 |
--------------------------------------------------------------------------------
/src/PartI_Basics/06-字典.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第六章 字典\n",
8 | "\n",
9 | "知识点:字典,键唯一值不要求,字典无序,访问,添加,修改,删除,语句过长拆分,for遍历的三种方法,字典和列表的各种相互嵌套"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "#### 字典可存储的信息几乎不受限制。理解字典后,就能够更准确地为各种真实物体建模\n",
17 | "\n",
18 | "#### 可以创建一个表示人的字典,然后在其中存储各种信息:姓名、年龄、地址、职业以及要描述的任何方面。\n",
19 | "\n",
20 | "#### 还能够存储任意两种相关的信息,如一系列单词及其含义,一系列人名及其喜欢的数字,以及一系列山脉及其海拔等。"
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "metadata": {},
26 | "source": [
27 | "## 6.1 一个简单的字典"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {},
33 | "source": [
34 | "### 小结:\n",
35 | "\n",
36 | "#### 格式:dictname = {'键': '值', '键': '值', '键': '值', … '键': '值'}\n",
37 | "#### 访问:dictname['键'],可赋值给变量存储后使用\n",
38 | "\n",
39 | "#### 考点:\n",
40 | "#### 键必须是唯一的,但值则不必。\n",
41 | "#### 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。"
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": 5,
47 | "metadata": {},
48 | "outputs": [
49 | {
50 | "name": "stdout",
51 | "output_type": "stream",
52 | "text": [
53 | "green\n",
54 | "5\n"
55 | ]
56 | }
57 | ],
58 | "source": [
59 | "# alien.py\n",
60 | "# 创建一个用于游戏的字典,存储关于特定外星人的信息,颜色、点数等。\n",
61 | "\n",
62 | "alien_0 = {'color':'green', 'points':5}\n",
63 | "\n",
64 | "print(alien_0['color'])\n",
65 | "print(alien_0['points'])"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {},
71 | "source": [
72 | "## 6.2 使用字典\n",
73 | "\n",
74 | "### 字典:‘键值对’,放在花括号里{},每个键都与一个值相关联,可使用键来访问与之相关联的值。\n",
75 | "### 键-值:两个相关联的值,指定键时,返回与之相关联的值;键和值冒号分隔,键-值对之间逗号分隔。\n",
76 | "### 值:可将python中任何对象用作字典中的值,比如数字、字符串、列表、字典等。"
77 | ]
78 | },
79 | {
80 | "cell_type": "markdown",
81 | "metadata": {},
82 | "source": [
83 | "### 小结:\n",
84 | "\n",
85 | "#### 在一个字典中,键值对的数量没有限制\n",
86 | "#### 访问字典中的值:dictname['键'],返回相关联的值\n",
87 | "#### 字典是无序的,而列表是有序的(可通过索引0-n进行访问,添加也是append到末尾,insert到对应位置)\n",
88 | "#### 添加键值对:dictname['键'] = '值',然后就将这对键值对添加到字典中的任意位置了\n",
89 | "#### 创建空字典后添加:dictname = {} 然后 dictname['键'] = '值'....进行添加\n",
90 | "#### 修改字典中的元素:dictname['键'] = '新值'\n",
91 | "#### 删除字典中的元素:del dictname['键'] -- del 字典名和键,就可以将该字典中的键值对删除\n",
92 | "#### 过长的一行语句的拆分,如print,+放在末尾;字典,逗号放在末尾,第二行四个空格"
93 | ]
94 | },
95 | {
96 | "cell_type": "code",
97 | "execution_count": 12,
98 | "metadata": {},
99 | "outputs": [
100 | {
101 | "name": "stdout",
102 | "output_type": "stream",
103 | "text": [
104 | "green\n",
105 | "You just earned 5 points!\n",
106 | "\n",
107 | "Alien_0:\n",
108 | "{'points': 5, 'color': 'green'}\n",
109 | "\n",
110 | "New alien_0:\n",
111 | "{'y_position': 25, 'points': 5, 'x_position': 0, 'color': 'green'}\n"
112 | ]
113 | }
114 | ],
115 | "source": [
116 | "# 在字典中,想存储多少个键-值对都可以。\n",
117 | "# 最简单的字典只有一个键-值对\n",
118 | "\n",
119 | "alien_0 = {'color':'green'}\n",
120 | "\n",
121 | "\n",
122 | "\n",
123 | "# 1-访问字典中的值\n",
124 | "# 依次指定字典名和放在方括号内的键\n",
125 | "print(alien_0['color'])\n",
126 | "\n",
127 | "# 字典可包含任意数量的键-值对。\n",
128 | "# 比如每当射杀外星人时,显示玩家应获得多少个点:\n",
129 | "alien_0 = {'color':'green', 'points':5}\n",
130 | "new_points = alien_0['points']\n",
131 | "print('You just earned ' + str(new_points) + ' points!')\n",
132 | "\n",
133 | "\n",
134 | "\n",
135 | "# 2-添加键-值对(排列与添加顺序无关,字典是无序的)\n",
136 | "# 依次指定字典名、用方括号括起来的键和相关联的值 字典名称[键]=值\n",
137 | "# 由于屏幕坐标系的原点通常为左上角,因此要将该外星人放在屏幕左边缘,可将 x 坐标设置为0;\n",
138 | "# 要将该外星人放在离屏幕顶部25像素的地方,可将 y 坐标设置为25\n",
139 | "print(\"\\nAlien_0:\")\n",
140 | "print(alien_0)\n",
141 | "\n",
142 | "alien_0['x_position']=0\n",
143 | "alien_0['y_position']=25\n",
144 | "print('\\nNew alien_0:')\n",
145 | "print(alien_0)"
146 | ]
147 | },
148 | {
149 | "cell_type": "code",
150 | "execution_count": 19,
151 | "metadata": {},
152 | "outputs": [
153 | {
154 | "name": "stdout",
155 | "output_type": "stream",
156 | "text": [
157 | "{'points': 5, 'color': 'green'}\n",
158 | "The alien is green.\n",
159 | "\n",
160 | "The alien is now yellow.\n",
161 | "\n",
162 | "Original x-positon: 0\n",
163 | "\n",
164 | "New x-position: 2\n",
165 | "\n",
166 | "The alien now is:\n",
167 | "{'points': 5, 'color': 'green'}\n",
168 | "\n",
169 | "The alien after delete:\n",
170 | "{'color': 'green'}\n"
171 | ]
172 | }
173 | ],
174 | "source": [
175 | "# alien.py\n",
176 | "# 3-先创建空字典后添加信息\n",
177 | "# 使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,通常都需要先定义一个空字典\n",
178 | "\n",
179 | "# 先使用一对空的花括号定义一个字典,再分行添加各个键-值对。\n",
180 | "alien_0 = {}\n",
181 | "alien_0['color'] = 'green'\n",
182 | "alien_0['points'] = 5\n",
183 | "print(alien_0)\n",
184 | "\n",
185 | "\n",
186 | "\n",
187 | "# 4-修改字典中的值\n",
188 | "# 随着游戏进行,需要将一个外星人由绿色变为黄色\n",
189 | "print('The alien is ' + alien_0['color']+'.')\n",
190 | "alien_0['color']='yellow'\n",
191 | "print('\\nThe alien is now ' + alien_0['color']+'.')\n",
192 | "\n",
193 | "# 对一个能够以不同速度移动的外星人的位置进行跟踪\n",
194 | "alien_0={'x_position':0, 'y_position':25, 'speed':'medium'}\n",
195 | "print('\\nOriginal x-positon: ' + str(alien_0['x_position']))\n",
196 | "\n",
197 | "# 向右移动外星人,根据外星人当前速度决定将其移动多远\n",
198 | "if alien_0['speed'] == 'slow':\n",
199 | " x_increment = 1 # increment-增量\n",
200 | "elif alien_0['speed'] == 'medium':\n",
201 | " x_increment = 2\n",
202 | "else:\n",
203 | " # 这个外星人速度一定很快\n",
204 | " x_increment = 3\n",
205 | "\n",
206 | "# 新位置等于老位置加上增量\n",
207 | "alien_0['x_position'] = alien_0['x_position'] + x_increment\n",
208 | "print('\\nNew x-position: ' + str(alien_0['x_position']))\n",
209 | "\n",
210 | "# 将速度中等的外星人变成速度很快的外星人\n",
211 | "alien_0['speed'] = 'fast'\n",
212 | "\n",
213 | "\n",
214 | "\n",
215 | "# 5-删除键-值对\n",
216 | "# del语句将不需要的信息彻底删除,必须指定字典名称和要删除的键\n",
217 | "alien_0 = {'color':'green', 'points':5}\n",
218 | "print('\\nThe alien now is:')\n",
219 | "print(alien_0)\n",
220 | "del alien_0['points']\n",
221 | "print('\\nThe alien after delete:')\n",
222 | "print(alien_0)"
223 | ]
224 | },
225 | {
226 | "cell_type": "code",
227 | "execution_count": 31,
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "name": "stdout",
232 | "output_type": "stream",
233 | "text": [
234 | "Sarah's favorite language is C.\n"
235 | ]
236 | }
237 | ],
238 | "source": [
239 | "# favorite_languages.py\n",
240 | "\n",
241 | "# 6-由类似对象组成的字典\n",
242 | "# 假设要调查很多人,询问他们最喜欢的编程语言\n",
243 | "\n",
244 | "# 同时演示了如何将过长的一行语句拆分,以及自己选择恰当的拆分位置,如print,+放在末尾;字典,逗号放在末尾\n",
245 | "favorite_languages = {\n",
246 | " 'jen':'python', # 4个空格\n",
247 | " 'sarah':'c',\n",
248 | " 'edward':'ruby',\n",
249 | " 'phil':'python',\n",
250 | " }\n",
251 | "\n",
252 | "print(\"Sarah's favorite language is \" + \n",
253 | " favorite_languages['sarah'].title() +\n",
254 | " '.')"
255 | ]
256 | },
257 | {
258 | "cell_type": "markdown",
259 | "metadata": {},
260 | "source": [
261 | "## 6.3 遍历字典\n",
262 | "\n",
263 | "### 遍历:for循环\n",
264 | "\n",
265 | "### 1-items()方法:所有键-值对\n",
266 | "### 2-keys()方法:所有键(可省略,加上使代码可读性更好)\n",
267 | "### 3-values()方法:所有值;set()函数:剔除重复元素"
268 | ]
269 | },
270 | {
271 | "cell_type": "markdown",
272 | "metadata": {},
273 | "source": [
274 | "### 小结:\n",
275 | "\n",
276 | "#### items() 方法:以列表形式返回可遍历的(键, 值) 元组数组(并非直接的列表,若要返回列表值还需调用list函数)\n",
277 | "#### items() 方法返回值:dict_items([('last', 'fermi'), ... , ('username', 'efermi')]) -- 元组里的列表里的以键值对为单位的元组\n",
278 | "#### \n",
279 | "#### items() + for循环:\n",
280 | "#### 格式:for a, b in list.items():... 无论如何命名,a和b一前一后分别对应键和值\n",
281 | "#### \n",
282 | "\n",
283 | "#### keys() 方法: 返回字典中的键\n",
284 | "#### \n",
285 | "#### keys() + for循环:\n",
286 | "#### 格式:for a in dictname.keys(): ...\n",
287 | "#### 提取字典dictname中的所有键,并依次将其存储到变量a中;遍历字典默认遍历键,keys()可省略\n",
288 | "#### 可在for循环中对返回的键进行排序。可使用函数sorted()来获取特定顺序排列的键列表的副本\n",
289 | "#### \n",
290 | "\n",
291 | "#### values() 方法:返回一个值列表,不包含任何键。\n",
292 | "#### \n",
293 | "\n",
294 | "#### values() + for循环:\n",
295 | "#### 格式:for a in dictname.values(): ... for语句提取字典中的每个值,并将它们依次存储到变量a中\n",
296 | "#### \n",
297 | "#### set()方法:\n",
298 | "#### (起因:键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。)\n",
299 | "#### 使用集合(set)可剔除重复项 - 类似于列表,但每个元素都是独一无二的\n",
300 | "#### set():对包含重复元素的列表调用set(),可找出列表中独一无二的元素,并使用这些元素创建一个集合\n",
301 | "#### 格式:for a in set(dictname.values()): .... "
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": 3,
307 | "metadata": {},
308 | "outputs": [
309 | {
310 | "name": "stdout",
311 | "output_type": "stream",
312 | "text": [
313 | "\n",
314 | "Key: username\n",
315 | "Value: efermi\n",
316 | "\n",
317 | "Key: first\n",
318 | "Value: enrico\n",
319 | "\n",
320 | "Key: last\n",
321 | "Value: fermi\n",
322 | "\n",
323 | "items()方法返回值:\n",
324 | "dict_items([('username', 'efermi'), ('first', 'enrico'), ('last', 'fermi')])\n",
325 | "\n",
326 | "\n",
327 | "Edward's favorite language is Ruby.\n",
328 | "Sarah's favorite language is C.\n",
329 | "Jen's favorite language is Python.\n",
330 | "Phil's favorite language is Python.\n",
331 | "Edward related to Ruby.\n",
332 | "Sarah related to C.\n",
333 | "Jen related to Python.\n",
334 | "Phil related to Python.\n"
335 | ]
336 | }
337 | ],
338 | "source": [
339 | "# user.py\n",
340 | "\n",
341 | "# 1-遍历所有的键-值对:\n",
342 | "# items()方法 + for循环\n",
343 | "# 要获悉该用户字典中的所有信息 - 使用一个for循环来遍历这个字典\n",
344 | "user_0 = {\n",
345 | " 'username':'efermi',\n",
346 | " 'first':'enrico',\n",
347 | " 'last':'fermi'\n",
348 | "}\n",
349 | "\n",
350 | "for key, value in user_0.items():\n",
351 | " # items()方法:以列表形式返回可遍历的(键, 值) 元组数组。(并非直接的列表,若要返回列表值还需调用list函数)\n",
352 | " print('\\nKey: ' + key)\n",
353 | " print('Value: ' + value)\n",
354 | " # 键-值对的返回顺序与存储顺序不同。python不关心存储顺序,只跟踪键和值之间的关联关系。\n",
355 | "\n",
356 | "print('\\nitems()方法返回值:')\n",
357 | "print(user_0.items())\n",
358 | "print('\\n')\n",
359 | "\n",
360 | "\n",
361 | "# favorite_languages.py\n",
362 | "favorite_languages = {\n",
363 | " 'jen':'python', # 4个空格\n",
364 | " 'sarah':'c',\n",
365 | " 'edward':'ruby',\n",
366 | " 'phil':'python',\n",
367 | " }\n",
368 | "\n",
369 | "for name, language in favorite_languages.items():\n",
370 | " print(name.title() + \"'s favorite language is \" + \n",
371 | " language.title() + '.')\n",
372 | "\n",
373 | "for a, b in favorite_languages.items(): # items()获取的键-值对分别对应给for后的两个变量,不论变量名是什么。\n",
374 | " print(a.title() + ' related to ' +\n",
375 | " b.title() + '.')"
376 | ]
377 | },
378 | {
379 | "cell_type": "code",
380 | "execution_count": 4,
381 | "metadata": {},
382 | "outputs": [
383 | {
384 | "name": "stdout",
385 | "output_type": "stream",
386 | "text": [
387 | "Edward\n",
388 | "Sarah\n",
389 | "Jen\n",
390 | "Phil\n",
391 | "\n",
392 | "\n",
393 | "Edward\n",
394 | "Sarah\n",
395 | " Hi Sarah, I see your favorite language is C!\n",
396 | "Jen\n",
397 | "Phil\n",
398 | " Hi Phil, I see your favorite language is Python!\n",
399 | "\n",
400 | "Eric, please take our poll!\n",
401 | "Edward, thank you for taking the poll.\n",
402 | "Jen, thank you for taking the poll.\n",
403 | "Phil, thank you for taking the poll.\n",
404 | "Sarah, thank you for taking the poll.\n",
405 | "\n",
406 | "The following languages have been mentioned:\n",
407 | "Ruby\n",
408 | "C\n",
409 | "Python\n",
410 | "Python\n",
411 | "\n",
412 | "After use the function set():\n",
413 | "Ruby\n",
414 | "Python\n",
415 | "C\n"
416 | ]
417 | }
418 | ],
419 | "source": [
420 | "# favorite_languages.py\n",
421 | "# 2-遍历字典中的所有键:keys()方法\n",
422 | "# 遍历字典时,默认遍历所有的键,所以上一行省略keys()完全没问题,但写上使代码更容易理解\n",
423 | "\n",
424 | "favorite_languages = {\n",
425 | " 'jen':'python',\n",
426 | " 'sarah':'c',\n",
427 | " 'edward':'ruby',\n",
428 | " 'phil':'python',\n",
429 | " }\n",
430 | "\n",
431 | "for name in favorite_languages.keys():\n",
432 | " # 提取字典favorite_languages 中的所有键,并依次将它们存储到变量name 中\n",
433 | " # 遍历字典时,默认遍历所有的键,所以上一行省略keys()完全没问题,但写上使代码更容易理解\n",
434 | " print(name.title()) \n",
435 | " \n",
436 | " \n",
437 | " \n",
438 | "# 在这种循环中,可使用当前键来访问与之相关联的值\n",
439 | "# 下面来打印两条消息,指出两位朋友喜欢的语言\n",
440 | "print('\\n')\n",
441 | "friends = ['phil', 'sarah']\n",
442 | "\n",
443 | "for name in favorite_languages.keys():\n",
444 | " print(name.title())\n",
445 | " if name in friends:\n",
446 | " print(\" Hi \" + name.title() +\n",
447 | " \", I see your favorite language is \" + \n",
448 | " favorite_languages[name].title() + '!')\n",
449 | " \n",
450 | "# 使用keys()确定某个人是否接受了调查\n",
451 | "if 'erin' not in favorite_languages.keys():\n",
452 | " print('\\nEric, please take our poll!')\n",
453 | " \n",
454 | " \n",
455 | " \n",
456 | "# 3-按顺序遍历字典中的所有键\n",
457 | "# 获取字典元素时,获取顺序是不可预测的。但通常你想要的只是获取与键相关联的正确的值\n",
458 | "# 要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。可使用函数sorted()来获取特定顺序排列的键列表的副本\n",
459 | "for name in sorted(favorite_languages.keys()): # 列出字典中的所有键,并在遍历前对这个列表进行排序\n",
460 | " print(name.title() + ', thank you for taking the poll.')\n",
461 | " \n",
462 | " \n",
463 | " \n",
464 | "# 4-遍历字典中的所有值:\n",
465 | "# values()方法-返回一个值列表,不包含任何键。\n",
466 | "print('\\nThe following languages have been mentioned:')\n",
467 | "for language in favorite_languages.values(): # for语句提取字典中的每个值,并将它们依次存储到变量language中\n",
468 | " print(language.title())\n",
469 | "\n",
470 | "# 上述方法没有考虑是否重复。\n",
471 | "# 使用集合(set)可剔除重复项 - 类似于列表,但每个元素都是独一无二的\n",
472 | "# set():对包含重复元素的列表调用set(),可让python找出列表中独一无二的元素,并使用这些元素创建一个集合\n",
473 | "print('\\nAfter use the function set():')\n",
474 | "for language in set(favorite_languages.values()):\n",
475 | " print(language.title())"
476 | ]
477 | },
478 | {
479 | "cell_type": "markdown",
480 | "metadata": {},
481 | "source": [
482 | "## 6.4 嵌套\n",
483 | "\n",
484 | "### 将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套\n",
485 | "### 可以在列表中嵌套字典、在字典中嵌套列表、在字典中嵌套字典"
486 | ]
487 | },
488 | {
489 | "cell_type": "markdown",
490 | "metadata": {},
491 | "source": [
492 | "### 小结:\n",
493 | "\n",
494 | "#### 在列表中嵌套字典:\n",
495 | "#### 格式:dict_1 = {} dict_2 = {} dict_3 = {} listname = [dict_1, dict_2, dict_3]\n",
496 | "#### \n",
497 | "\n",
498 | "#### 在字典中嵌套列表:当需要在字典中将一个键关联到多个值时\n",
499 | "#### 格式:dictname = {'键':'值', '键': [a, b, c, ... , m]} --- 例子中第二个键关联到a-m等多个值\n",
500 | "#### 此时若用for循环遍历字典,需要两层for循环\n",
501 | "#### \n",
502 | " \n",
503 | "#### 在字典中嵌套字典:\n",
504 | "#### 格式:dictname = { '键1': {字典1}, '键2': {字典2}, ... , '键n': {字典n} }"
505 | ]
506 | },
507 | {
508 | "cell_type": "code",
509 | "execution_count": 58,
510 | "metadata": {},
511 | "outputs": [
512 | {
513 | "name": "stdout",
514 | "output_type": "stream",
515 | "text": [
516 | "{'points': 5, 'color': 'green'}\n",
517 | "{'points': 10, 'color': 'yellow'}\n",
518 | "{'points': 15, 'color': 'red'}\n",
519 | "\n",
520 | "30 aliens:\n",
521 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
522 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
523 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
524 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
525 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
526 | "...\n",
527 | "Total number of aliens: 30\n",
528 | "\n",
529 | "Change some aliens:\n",
530 | "{'points': 10, 'color': 'yellow', 'speed': 'medium'}\n",
531 | "{'points': 10, 'color': 'yellow', 'speed': 'medium'}\n",
532 | "{'points': 10, 'color': 'yellow', 'speed': 'medium'}\n",
533 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
534 | "{'points': 5, 'color': 'green', 'speed': 'slow'}\n",
535 | "...\n"
536 | ]
537 | }
538 | ],
539 | "source": [
540 | "# aliens.py\n",
541 | "# 1-字典列表\n",
542 | "# 管理多个外星人:创建一个外星人列表,其中每个外星人都是一个字典\n",
543 | "\n",
544 | "alien_0 = {'color':'green', 'points':5}\n",
545 | "alien_1 = {'color':'yellow', 'points':10}\n",
546 | "alien_2 = {'color':'red', 'points':15}\n",
547 | "\n",
548 | "aliens = [alien_0, alien_1, alien_2] # 将上述多个字典都放到一个名为aliens的列表中\n",
549 | "for alien in aliens: # 遍历这个aliens列表\n",
550 | " print(alien)\n",
551 | " \n",
552 | " \n",
553 | " \n",
554 | "# 管理多个字典:用range()生成30个外星人\n",
555 | "# 创建一个用于存储外星人的空列表\n",
556 | "print('\\n30 aliens:')\n",
557 | "aliens = []\n",
558 | "\n",
559 | "# 创建30个绿色的外星人\n",
560 | "for alien_number in range(30): # range()返回一系列数字,这里告诉python需要重复多少次循环\n",
561 | " new_alien = {'color':'green', 'points':5, 'speed':'slow'}\n",
562 | " aliens.append(new_alien)\n",
563 | " \n",
564 | "# 显示前五个外星人\n",
565 | "for alien in aliens[:5]: # 使用一个切片来打印前五个外星人\n",
566 | " print(alien)\n",
567 | "print('...')\n",
568 | "\n",
569 | "# 显示创建了多少个外星人\n",
570 | "print('Total number of aliens: ' + str(len(aliens)))\n",
571 | "\n",
572 | "\n",
573 | "\n",
574 | "# 每个外星人都是独立的\n",
575 | "# 可以使用for循环和if语句来修改某些特征:比如修改前三个外星人的特征值为‘中-10-黄色’\n",
576 | "# 添加elif模块可将黄色外星人修改为快-15-红色外星人\n",
577 | "print('\\nChange some aliens:')\n",
578 | "for alien in aliens[0:3]:\n",
579 | " if alien['color'] == 'green':\n",
580 | " alien['color'] = 'yellow'\n",
581 | " alien['speed'] = 'medium'\n",
582 | " alien['points'] = 10\n",
583 | " elif alien['color'] == 'yellow':\n",
584 | " alien['color'] = 'red'\n",
585 | " alien['speed'] = 'fast'\n",
586 | " alien['points'] = 15\n",
587 | " \n",
588 | "# 显示前五个外星人\n",
589 | "for alien in aliens[0:5]:\n",
590 | " print(alien)\n",
591 | "print('...')"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "execution_count": 60,
597 | "metadata": {},
598 | "outputs": [
599 | {
600 | "name": "stdout",
601 | "output_type": "stream",
602 | "text": [
603 | "You ordered a thick-crust pizza with the following toppings:\n",
604 | "\tmushrooms\n",
605 | "\textra cheese\n",
606 | "\n",
607 | "Phil's favorite languages are:\n",
608 | "\tPython\n",
609 | "\tHaskell\n",
610 | "\n",
611 | "Jen's favorite languages are:\n",
612 | "\tPython\n",
613 | "\tRuby\n",
614 | "\n",
615 | "Sarah's favorite languages are:\n",
616 | "\tC\n",
617 | "\n",
618 | "Edward's favorite languages are:\n",
619 | "\tRuby\n",
620 | "\tGo\n"
621 | ]
622 | }
623 | ],
624 | "source": [
625 | "# pizza.py\n",
626 | "# 2-在字典中存储列表\n",
627 | "# 每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表\n",
628 | "\n",
629 | "# 描述顾客点的比萨:如果使用列表,只能存储要添加的配料;如果使用字典,还可包含其他有关比萨的描述\n",
630 | "\n",
631 | "# 存储所点比萨的信息\n",
632 | "pizza = {\n",
633 | " 'crust':'thick',\n",
634 | " 'toppings':['mushrooms','extra cheese'],\n",
635 | " }\n",
636 | "\n",
637 | "# 概述所点的比萨\n",
638 | "print('You ordered a ' + pizza['crust'] + '-crust pizza ' +\n",
639 | " 'with the following toppings:')\n",
640 | "for topping in pizza['toppings']:\n",
641 | " print('\\t' + topping)\n",
642 | " \n",
643 | " \n",
644 | " \n",
645 | "# favorite_languages.py\n",
646 | "# 将每个人的回答都存储在一个列表中,被调查者就可选择多种喜欢的语言。\n",
647 | "# 遍历字典时,与每个被调查者相关联的都是一个语言列表,而不是一种语言;\n",
648 | "# 因此,在遍历该字典的for 循环中,我们需要再使用一个for循环来遍历与被调查者相关联的语言列表:\n",
649 | "favorite_languages = {\n",
650 | " 'jen':['python','ruby'],\n",
651 | " 'sarah':['c'],\n",
652 | " 'edward':['ruby','go'],\n",
653 | " 'phil':['python','haskell'],\n",
654 | " }\n",
655 | "\n",
656 | "for name, languages in favorite_languages.items():\n",
657 | " print('\\n' + name.title() + \"'s favorite languages are:\")\n",
658 | " for language in languages:\n",
659 | " print('\\t' + language.title())"
660 | ]
661 | },
662 | {
663 | "cell_type": "code",
664 | "execution_count": 63,
665 | "metadata": {
666 | "scrolled": true
667 | },
668 | "outputs": [
669 | {
670 | "name": "stdout",
671 | "output_type": "stream",
672 | "text": [
673 | "\n",
674 | "Username: aeinstein\n",
675 | "\tFull name: Albert Einstein\n",
676 | "\tLocation: Princeton\n",
677 | "\n",
678 | "Username: mcurie\n",
679 | "\tFull name: Marie Curie\n",
680 | "\tLocation: Paris\n"
681 | ]
682 | }
683 | ],
684 | "source": [
685 | "# many_users.py\n",
686 | "# 3-在字典中存储字典\n",
687 | "\n",
688 | "# 有多个网站用户,每个都有独特的用户名的情况下:\n",
689 | "# 可在字典中将用户名作为键,将每位用户的信息存储在一个字典中作为与用户名相关联的值\n",
690 | "# 如下:对每位用户,存储三项信息 - 名、姓、居住地\n",
691 | "users = {\n",
692 | " 'aeinstein':{\n",
693 | " 'first':'albert',\n",
694 | " 'last':'einstein',\n",
695 | " 'location':'princeton'\n",
696 | " },\n",
697 | " \n",
698 | " 'mcurie':{\n",
699 | " 'first':'marie',\n",
700 | " 'last':'curie',\n",
701 | " 'location':'paris',\n",
702 | " },\n",
703 | " }\n",
704 | "\n",
705 | "for username, user_info in users.items():\n",
706 | " print('\\nUsername: ' + username)\n",
707 | " full_name = user_info['first'] + ' ' + user_info['last']\n",
708 | " location = user_info['location']\n",
709 | " \n",
710 | " print('\\tFull name: ' + full_name.title())\n",
711 | " print('\\tLocation: ' + location.title())"
712 | ]
713 | },
714 | {
715 | "cell_type": "code",
716 | "execution_count": null,
717 | "metadata": {},
718 | "outputs": [],
719 | "source": []
720 | }
721 | ],
722 | "metadata": {
723 | "kernelspec": {
724 | "display_name": "Python 3",
725 | "language": "python",
726 | "name": "python3"
727 | },
728 | "language_info": {
729 | "codemirror_mode": {
730 | "name": "ipython",
731 | "version": 3
732 | },
733 | "file_extension": ".py",
734 | "mimetype": "text/x-python",
735 | "name": "python",
736 | "nbconvert_exporter": "python",
737 | "pygments_lexer": "ipython3",
738 | "version": "3.7.0"
739 | }
740 | },
741 | "nbformat": 4,
742 | "nbformat_minor": 2
743 | }
744 |
--------------------------------------------------------------------------------
/src/PartI_Basics/07-用户输入和while循环.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 第七章 用户输入和while循环\n",
8 | "\n",
9 | "知识点:input(),求模运算%,while循环,标志(封装的布尔表达式),break退出循环,while循环处理字典和列表(列表间移动元素、删除列表中多次出现的元素、input填充字典)"
10 | ]
11 | },
12 | {
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "## 7.1 函数input()的工作原理\n",
17 | "\n",
18 | "### 函数input():\n",
19 | "### 让程序暂停运行,等待用户输入一些文本。获取用户输入后,将其存储在一个变量中。回车继续运行。\n",
20 | "### input()接收一个参数:即要向用户显示的提示或说明(放在函数的圆括号里)\n",
21 | "### input():将用户输入默认为字符串 - int()函数转为数值使用"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {},
27 | "source": [
28 | "### 小结:\n",
29 | "\n",
30 | "#### input(参数):暂停程序,展示括号中的参数,等待用户输入,回车继续运行,并返回输入的值\n",
31 | "#### input():默认返回值是字符串,可用int()将str转为数值型,可将存储input返回值的变量放在int()中,或直接int(input())\n",
32 | "#### 求模运算符:% -- 将两数相除并返回余数 -- 格式:m % n"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": 64,
38 | "metadata": {},
39 | "outputs": [
40 | {
41 | "name": "stdout",
42 | "output_type": "stream",
43 | "text": [
44 | "Tell me something, and I will repeat it back to you: hello how are you\n",
45 | "hello how are you\n"
46 | ]
47 | }
48 | ],
49 | "source": [
50 | "# parrot.py\n",
51 | "\n",
52 | "# input()接收一个参数:即要向用户显示的提示或说明\n",
53 | "message = input('Tell me something, and I will repeat it back to you: ')\n",
54 | "print(message)"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": 71,
60 | "metadata": {},
61 | "outputs": [
62 | {
63 | "name": "stdout",
64 | "output_type": "stream",
65 | "text": [
66 | "Please enter your name: Name_1\n",
67 | "Hello, Name_1!\n",
68 | "\n",
69 | "If you tell us who you are, we can personalize the messages you see.\n",
70 | "What is your first name? Name_2\n",
71 | "\n",
72 | "Hello, Name_2!\n",
73 | "\n",
74 | "How old are you? 22\n",
75 | "True\n"
76 | ]
77 | }
78 | ],
79 | "source": [
80 | "# greeter.py\n",
81 | "# 1-编写清晰的程序\n",
82 | "name = input('Please enter your name: ')\n",
83 | "print('Hello, ' + name + '!')\n",
84 | "\n",
85 | "\n",
86 | "# 提示超过一行时,可将提示存储在一个变量中,再讲该变量传递给函数input()\n",
87 | "prompt = '\\nIf you tell us who you are, we can personalize the messages you see.'\n",
88 | "prompt += '\\nWhat is your first name? '\n",
89 | "name = input(prompt)\n",
90 | "print('\\nHello, ' + name + '!')\n",
91 | "\n",
92 | "\n",
93 | "\n",
94 | "# 2-使用int()来获取数值输入 - 类型转换为int型\n",
95 | "age = input('\\nHow old are you? ')\n",
96 | "age = int(age)\n",
97 | "print(age >= 18)"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": 72,
103 | "metadata": {},
104 | "outputs": [
105 | {
106 | "name": "stdout",
107 | "output_type": "stream",
108 | "text": [
109 | "How tall are you, in inches? 24\n",
110 | "\n",
111 | "You will be able to ride when you are a little older.\n"
112 | ]
113 | }
114 | ],
115 | "source": [
116 | "# rollercoaster.py\n",
117 | "# 判断一个人是否满足坐过山车的身高要求:\n",
118 | "\n",
119 | "height = input('How tall are you, in inches? ')\n",
120 | "height = int(height)\n",
121 | "if height >= 36:\n",
122 | " print('\\nYou are tall enough to ride.')\n",
123 | "else:\n",
124 | " print('\\nYou will be able to ride when you are a little older.')"
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": 75,
130 | "metadata": {},
131 | "outputs": [
132 | {
133 | "name": "stdout",
134 | "output_type": "stream",
135 | "text": [
136 | "1\n",
137 | "2\n",
138 | "0\n",
139 | "1\n",
140 | "\n",
141 | "Enter a number, and I will tell you if it is even or odd: 23\n",
142 | "\n",
143 | "The number 23 is odd.\n"
144 | ]
145 | }
146 | ],
147 | "source": [
148 | "# 3-求模运算符(%) - 将两数相除并返回余数\n",
149 | "print(4 % 3) # 余1\n",
150 | "print(5 % 3) # 余2\n",
151 | "print(6 % 3) # 余0\n",
152 | "print(7 % 3) # 余1\n",
153 | "\n",
154 | "\n",
155 | "\n",
156 | "# even_or_odd.py\n",
157 | "# 利用取余判断一个数是奇数还是偶数\n",
158 | "number = input('\\nEnter a number, and I will tell you if it is even or odd: ')\n",
159 | "number = int(number)\n",
160 | "if number % 2 == 0:\n",
161 | " print('\\nThe number ' + str(number) + ' is even.') # 要和一堆字符串连在一起,number需要转换为字符串\n",
162 | "else:\n",
163 | " print('\\nThe number ' + str(number) + ' is odd.')"
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "metadata": {},
169 | "source": [
170 | "## 7.2 while循环简介\n",
171 | "#### for循环:用于针对集合中的每个元素都一个代码块\n",
172 | "#### while循环:不断运行,直到指定的条件不满足为止"
173 | ]
174 | },
175 | {
176 | "cell_type": "markdown",
177 | "metadata": {},
178 | "source": [
179 | "### 小结:\n",
180 | "\n",
181 | "#### while循环格式:while 语句: xxx xxx .. xx(可内含多条语句)\n",
182 | "\n",
183 | "#### 标志:定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为‘标志’\n",
184 | "#### 标志的好处:while只需检查标志一个条件,并将所有测试 (是否发生了应将标志设置为False的事件) 都放在其他地方,使程序更为整洁\n",
185 | "\n",
186 | "#### break退出循环:立即退出循环,不再运行循环中余下的代码,也不管条件测试的结果如何\n",
187 | "#### break循环:可以用在任何Python循环中,例如,退出遍历列表或字典的for循环"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 2,
193 | "metadata": {},
194 | "outputs": [
195 | {
196 | "name": "stdout",
197 | "output_type": "stream",
198 | "text": [
199 | "1\n",
200 | "2\n",
201 | "3\n",
202 | "4\n",
203 | "5\n",
204 | "\n",
205 | "Tell me something, and I will repeat it back to you:\n",
206 | "Enter 'quit' to end the program. abc\n",
207 | "abc\n",
208 | "\n",
209 | "Tell me something, and I will repeat it back to you:\n",
210 | "Enter 'quit' to end the program. quit\n"
211 | ]
212 | }
213 | ],
214 | "source": [
215 | "# counting.py\n",
216 | "# 1-使用while循环\n",
217 | "current_number = 1\n",
218 | "while current_number <= 5:\n",
219 | " print(current_number)\n",
220 | " current_number += 1\n",
221 | " \n",
222 | " \n",
223 | " \n",
224 | "# parrot.py\n",
225 | "# 2-让用户选择何时退出\n",
226 | "prompt = '\\nTell me something, and I will repeat it back to you:'\n",
227 | "prompt += \"\\nEnter 'quit' to end the program. \"\n",
228 | "message = ''\n",
229 | "while message != 'quit':\n",
230 | " message = input(prompt)\n",
231 | " if message != 'quit': # 当输入quit时,quit不打印\n",
232 | " print(message)"
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": 3,
238 | "metadata": {},
239 | "outputs": [
240 | {
241 | "name": "stdout",
242 | "output_type": "stream",
243 | "text": [
244 | "\n",
245 | "Tell me something, and I will repeat it back to you:\n",
246 | "Enter 'quit' to end the program. Hello, how r you\n",
247 | "Hello, how r you\n",
248 | "\n",
249 | "Tell me something, and I will repeat it back to you:\n",
250 | "Enter 'quit' to end the program. quit\n"
251 | ]
252 | }
253 | ],
254 | "source": [
255 | "# parrot.py\n",
256 | "# 3-使用标志\n",
257 | "# 定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为‘标志’\n",
258 | "# 标志-充当程序的交通信号灯,为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。\n",
259 | "# while只需检查标志一个条件,并将所有测试(是否发生了应将标志设置为False的事件)都放在其他地方,使程序更为整洁\n",
260 | "\n",
261 | "# 在前一小节的程序中,添加一个标志,命名为activate(可指定任何名称),用于判断程序是否应继续运行\n",
262 | "prompt = '\\nTell me something, and I will repeat it back to you:'\n",
263 | "prompt += \"\\nEnter 'quit' to end the program. \"\n",
264 | "\n",
265 | "active = True\n",
266 | "while active:\n",
267 | " # 使用一个标志来指出程序是否处于活动状态,这样如果需要添加测试(如elif语句),将很容易。\n",
268 | " message = input(prompt)\n",
269 | " if message == 'quit':\n",
270 | " active = False\n",
271 | " else:\n",
272 | " print(message)"
273 | ]
274 | },
275 | {
276 | "cell_type": "code",
277 | "execution_count": 4,
278 | "metadata": {},
279 | "outputs": [
280 | {
281 | "name": "stdout",
282 | "output_type": "stream",
283 | "text": [
284 | "\n",
285 | "Please enter the name of a city you hava visited:\n",
286 | "(Enter 'quit' when you are finished.) Tianjin\n",
287 | "I'd love to go to Tianjin!\n",
288 | "\n",
289 | "Please enter the name of a city you hava visited:\n",
290 | "(Enter 'quit' when you are finished.) quit\n"
291 | ]
292 | }
293 | ],
294 | "source": [
295 | "# cities.py\n",
296 | "# 4-使用break退出循环:立即退出循环,不再运行循环中余下的代码,也不管条件测试的结果如何\n",
297 | "\n",
298 | "# 注意:在任何Python循环中都可使用break 语句。例如,可使用break 语句来退出遍历列表或字典的for 循环。\n",
299 | "\n",
300 | "# 让用户指出他到过哪些地方\n",
301 | "prompt = '\\nPlease enter the name of a city you hava visited:'\n",
302 | "prompt += \"\\n(Enter 'quit' when you are finished.) \"\n",
303 | "\n",
304 | "while True:\n",
305 | " city = input(prompt)\n",
306 | " \n",
307 | " if city == 'quit':\n",
308 | " break\n",
309 | " else:\n",
310 | " print(\"I'd love to go to \" + city.title() + '!')"
311 | ]
312 | },
313 | {
314 | "cell_type": "code",
315 | "execution_count": 7,
316 | "metadata": {},
317 | "outputs": [
318 | {
319 | "name": "stdout",
320 | "output_type": "stream",
321 | "text": [
322 | "1\n",
323 | "3\n",
324 | "5\n",
325 | "7\n",
326 | "9\n",
327 | "1\n",
328 | "2\n",
329 | "3\n",
330 | "4\n",
331 | "5\n"
332 | ]
333 | }
334 | ],
335 | "source": [
336 | "# counting.py\n",
337 | "# 5-在循环中使用continue:返回到循环开头,并根据条件测试结果决定是否继续执行循环\n",
338 | "\n",
339 | "# 10以内的数,打印出其中的奇数\n",
340 | "current_number = 0\n",
341 | "while current_number < 10:\n",
342 | " current_number += 1\n",
343 | " if current_number % 2 == 0:\n",
344 | " continue\n",
345 | " # 当current_number能被2整除,就执行continue,让Python忽略余下的代码,并返回循环开头。\n",
346 | " # 如果不能被2整除,就执行余下的代码,打印该数字\n",
347 | " \n",
348 | " # 注意:print是与if语句模块平级的,if不成立时,顺序执行print语句的内容\n",
349 | " print(current_number)\n",
350 | " \n",
351 | " \n",
352 | " \n",
353 | "# 6-避免无限循环\n",
354 | "x = 1\n",
355 | "while x <= 5:\n",
356 | " print(x)\n",
357 | " x += 1 # 当漏写这条语句时,程序会陷入无限循环\n",
358 | " # 当程序陷入无限循环时,可按Ctrl+c,也可关闭显示程序输出的终端窗口\n",
359 | " # jupyter notebook中按Ctrl-c不管用,点上边的小方块‘中断服务’可中断"
360 | ]
361 | },
362 | {
363 | "cell_type": "markdown",
364 | "metadata": {},
365 | "source": [
366 | "## 7.3 使用while循环来处理列表和字典\n",
367 | "\n",
368 | "### 当需要记录大量数据时使用\n",
369 | "### for循环是一种遍历列表的有效方式,但不应修改列表,否则将导致Python难以跟踪其中的元素\n",
370 | "### 要在遍历列表的同时对其修改,可使用while循环\n",
371 | "### 通过while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示"
372 | ]
373 | },
374 | {
375 | "cell_type": "markdown",
376 | "metadata": {},
377 | "source": [
378 | "### 小结:\n",
379 | "\n",
380 | "#### 在列表之间移动元素: while list_1: a = list_1.pop() list_2.append(a) --- 可将list_1中的元素逐渐移动到list_2中\n",
381 | "#### 删除一个列表中多次出现的元素:while 'xx' in listname: listname.remove('xx') \n",
382 | "#### 使用用户输入填充字典:创建空字典--标志=True--while 标志: xx xxx xx input -- if xx: 标志 = False"
383 | ]
384 | },
385 | {
386 | "cell_type": "code",
387 | "execution_count": 2,
388 | "metadata": {},
389 | "outputs": [
390 | {
391 | "name": "stdout",
392 | "output_type": "stream",
393 | "text": [
394 | "Verifying user: Candace\n",
395 | "Verifying user: Brian\n",
396 | "Verifying user: Alice\n",
397 | "\n",
398 | "The following users have been confirmed:\n",
399 | "Candace\n",
400 | "Brian\n",
401 | "Alice\n"
402 | ]
403 | }
404 | ],
405 | "source": [
406 | "# confirmed_users.py\n",
407 | "# 1-在列表之间移动元素\n",
408 | "\n",
409 | "# 一个列表,包含新注册但未验证用户;验证后,将其移动到另一个已验证用户列表中\n",
410 | "# 先创建一个待验证用户列表和一个用于存储已验证用户的空列表\n",
411 | "unconfirmed_users = ['alice','brian','candace']\n",
412 | "confirmed_users = []\n",
413 | "\n",
414 | "# 验证每个用户,直到没有未验证用户为止\n",
415 | "# 将每个经过验证的列表都移到已验证用户列表中\n",
416 | "while unconfirmed_users:\n",
417 | " current_user = unconfirmed_users.pop() # pop类似于弹栈,弹出最后一个(不在括号内指定索引时) - 3.2章出现过\n",
418 | " \n",
419 | " print('Verifying user: ' + current_user.title())\n",
420 | " confirmed_users.append(current_user)\n",
421 | " \n",
422 | "# 显示所有已验证的用户\n",
423 | "print('\\nThe following users have been confirmed:')\n",
424 | "for confirmed_user in confirmed_users:\n",
425 | " print(confirmed_user.title())"
426 | ]
427 | },
428 | {
429 | "cell_type": "code",
430 | "execution_count": 4,
431 | "metadata": {},
432 | "outputs": [
433 | {
434 | "name": "stdout",
435 | "output_type": "stream",
436 | "text": [
437 | "['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']\n",
438 | "['dog', 'dog', 'goldfish', 'rabbit']\n"
439 | ]
440 | }
441 | ],
442 | "source": [
443 | "# pets.py\n",
444 | "# 2-删除包含特定值的所有列表元素\n",
445 | "# 之前学到,remove()方法,可删除列表中特定值(要删除的值在列表中只出现一次) - 3.2章出现过\n",
446 | "\n",
447 | "# 一个宠物列表,其中包含多个‘cat’。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含‘cat’\n",
448 | "pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']\n",
449 | "print(pets)\n",
450 | "\n",
451 | "while 'cat' in pets: # in:首次出现在for语句 - for i in something (for语句中的in貌似也是一种布尔表达式...)\n",
452 | " # 5.2章-布尔表达式:检查特定值是否包含在列表中: 'x' in list_name - True or False\n",
453 | " pets.remove('cat')\n",
454 | "\n",
455 | "print(pets)"
456 | ]
457 | },
458 | {
459 | "cell_type": "code",
460 | "execution_count": 6,
461 | "metadata": {
462 | "scrolled": true
463 | },
464 | "outputs": [
465 | {
466 | "name": "stdout",
467 | "output_type": "stream",
468 | "text": [
469 | "\n",
470 | "What is your name? tom\n",
471 | "Which mountain would you like to climeb someday? abs\n",
472 | "Would you like to let another person response? (yes/no) peter\n",
473 | "\n",
474 | "What is your name? bas\n",
475 | "Which mountain would you like to climeb someday? no\n",
476 | "Would you like to let another person response? (yes/no) no\n",
477 | "\n",
478 | "--- Poll Results ---\n",
479 | "tom would like to climb abs.\n",
480 | "bas would like to climb no.\n"
481 | ]
482 | }
483 | ],
484 | "source": [
485 | "# mountain_poll.py\n",
486 | "# 3-使用用户输入来填充字典\n",
487 | "\n",
488 | "# 一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。\n",
489 | "# 将收集到的数据存储在一个字典中,以便将回答同被调查者关联起来\n",
490 | "responses = {}\n",
491 | "\n",
492 | "# 设置一个标志,指出调查是否继续\n",
493 | "polling_active = True\n",
494 | "\n",
495 | "while polling_active:\n",
496 | " # 提示输入被调查者的名字和回答\n",
497 | " name = input('\\nWhat is your name? ')\n",
498 | " response = input('Which mountain would you like to climeb someday? ')\n",
499 | " \n",
500 | " # 将答卷存储在字典中\n",
501 | " responses[name] = response\n",
502 | " \n",
503 | " # 看看是否还有人要参与调查\n",
504 | " # 如果input-yes,则polling_active没有变成False,就在循环内所有语句都执行之后,继续重新开始一轮循环\n",
505 | " repeat = input('Would you like to let another person response? (yes/no) ')\n",
506 | " if repeat == 'no':\n",
507 | " polling_active = False\n",
508 | " \n",
509 | "# 调查结束,显示结果\n",
510 | "print('\\n--- Poll Results ---')\n",
511 | "for name, response in responses.items():\n",
512 | " print(name + ' would like to climb ' + response + '.')"
513 | ]
514 | }
515 | ],
516 | "metadata": {
517 | "kernelspec": {
518 | "display_name": "Python 3",
519 | "language": "python",
520 | "name": "python3"
521 | },
522 | "language_info": {
523 | "codemirror_mode": {
524 | "name": "ipython",
525 | "version": 3
526 | },
527 | "file_extension": ".py",
528 | "mimetype": "text/x-python",
529 | "name": "python",
530 | "nbconvert_exporter": "python",
531 | "pygments_lexer": "ipython3",
532 | "version": "3.7.0"
533 | }
534 | },
535 | "nbformat": 4,
536 | "nbformat_minor": 2
537 | }
538 |
--------------------------------------------------------------------------------
/src/PartI_Basics/README.md:
--------------------------------------------------------------------------------
1 | # 第一部分-基础篇
2 |
3 |
4 | ## 目录:
5 |
6 | * [00 综](#00-综)
7 | * [01 起步](#01-起步)
8 | * [02 变量和简单数据类型](#02-变量和简单数据类型)
9 | * [03 列表简介](#03-列表简介)
10 | * [04 操作列表](#04-操作列表)
11 | * [05 if语句](#05-if语句)
12 | * [06 字典](#06-字典)
13 | * [07 用户输入和while循环](#07-用户输入和while循环)
14 | * [08 函数](#08-函数)
15 | * [09 类](#09-类)
16 | * [10 文件和异常](#10-文件和异常)
17 | * [11 测试代码](#11-测试代码)
18 |
19 |
20 |
21 | ## 说明
22 | - 笔记文件为.ipybn格式,内含全部代码及相应的笔记
23 | - .ipynb文件若加载失败,可使用此链接打开 [https://nbviewer.jupyter.org/github/...]
24 | - 例如:https://nbviewer.jupyter.org/github/anliux/Python_Crash_Course/blob/master/src/PartI_Basics/A_Basics_Note.ipynb
25 |
26 | # 00 综
27 | - [《综》](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/A_Basics_Note.ipynb)
28 | - [备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/A_Basics_Note.ipynb)
29 | - 各章汇总
30 |
31 |
32 | - [返回目录](#目录)
33 |
34 |
35 |
36 | # 01 起步
37 | - [第1章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/01-%E8%B5%B7%E6%AD%A5.ipynb)
38 | - [第1章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/01-%E8%B5%B7%E6%AD%A5.ipynb)
39 | - 知识点:
40 | - 打印hello world:`print('要打印的内容')`
41 | - 注意点:单双引号均可,没有分号。
42 | - 打印的参数化:`print('min=%d' %min(digits))`
43 | - 换行:\n放在引号内打印 -- `print('\n')`
44 | - 制表符:\t放在引号内打印 -- `print('\t')`
45 |
46 |
47 | - [返回目录](#目录)
48 |
49 |
50 |
51 |
52 | # 02 变量和简单数据类型
53 | - [第2章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/02-%E5%8F%98%E9%87%8F%E5%92%8C%E7%AE%80%E5%8D%95%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb)
54 | - [第2章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/02-%E5%8F%98%E9%87%8F%E5%92%8C%E7%AE%80%E5%8D%95%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb)
55 | - 知识点:
56 | - 汇总:
57 | - 认识变量、变量名规则、单双引号、字符串(大小写、拼接、空白)、数字(简单计算-除法、次方)、注释(单行多行)
58 | - python变量名:
59 | - 大写无妨,尽量用小写;
60 | - 字母数字下划线,数字不能开头,中间不能空格,并且慎用小写字母L和大写字母O(与数字0,1非常相似)
61 | - Python约定的文件名:
62 | - 使用小写字母和下划线
63 | - 引号:
64 | - 单引号双引号均可,灵活使用有助于撇号的使用,单双均可在外。
65 | - 单双引号的灵活使用:普通用单;双嵌套单,英语中常用的缩写一撇等等
66 | - 字符串:(大小写、拼接、空白)
67 | - 格式:`变量.方法名()`
68 | - title() - 改为首字母大写、其余小写
69 | - upper() - 改为所有字母大写
70 | - lower() - 改为所有字母小写
71 | - + :拼接字符串
72 | - 制表符:\t
73 | - 换行: \n
74 | - strip() - 删除空白
75 | - rstrip() - 删除右边的空白
76 | - lstrip() - 删除左边的空白
77 | - 数字:(简单计算-除法、次方)
78 | - py3的float不能精确显示(例如:0.1 + 0.2=0.30000000000000004)
79 | - 整数相除,结果为float类型(Python2的整数相除为int型,同其他语言)
80 | - 两个星号 * :乘方,相当于^
81 | - 用+号连接str和int时,将int转为str:当int x, str(x)后在加号连接
82 | - Python之禅
83 | - 美胜于丑。
84 | - 显式优于隐式。
85 | - 简单胜于复杂。
86 | - 复杂总比复杂好。
87 | - 平的比嵌套的好。
88 | - 稀疏胜于稠密。
89 | - 可读性计数。
90 | - 特殊情况不足以打破规则。
91 | - 尽管实用性胜过纯洁性。
92 | - 错误永远不会悄悄地过去。
93 | - 除非明确沉默。
94 | - 面对歧义,拒绝猜测的诱惑。
95 | - 应该有一种——最好只有一种——显而易见的方法来做到这一点。
96 | - 不过,如果不是荷兰语的话,这种方式一开始可能并不明显。
97 | - 现在总比没有好。
98 | - 虽然从来没有比现在更好。
99 | - 如果实现很难解释,那是个坏主意。
100 | - 如果实现很容易解释,这可能是一个好主意。
101 | - 名称空间是一个非常好的主意——让我们做更多的事情吧!
102 |
103 |
104 | - [返回目录](#目录)
105 |
106 |
107 |
108 |
109 | # 03 列表简介
110 | - [第3章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/03-%E5%88%97%E8%A1%A8%E7%AE%80%E4%BB%8B.ipynb)
111 | - [第3章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/03-%E5%88%97%E8%A1%A8%E7%AE%80%E4%BB%8B.ipynb)
112 | - 知识点:
113 | - 汇总:列表的认识、创建、访问单个元素、修改、添加、删除、字母表排序、反转排序、求列表长度、索引注意事项
114 | - 认识列表:
115 | - 用方括号([ ] )来表示列表,并用逗号来分隔其中的元素,print时包括方括号、引号、逗号等
116 | - 由一系列按特定顺序排列的元素组成; 可以将任何东西加入列表中
117 | - 创建和访问列表:
118 | - 列表的格式:listname = [ , , , , ] --- 方括号,逗号隔开
119 | - 列表的访问:listname[n] -- 按索引n访问列表
120 | - 索引从0开始(同数组),负数表示倒数第几个
121 | - 修改、添加、删除列表元素
122 | - 修改:listname[n] = '新' -- 将索引n对应的元素换位'新'
123 | - 添加:listname.append('新') -- 将'新'添加到list的末尾
124 | - 动态地创建列表:先创建空列表,然后一系列append添加 -- listname=[] \\ listname.append('新') \\ listname.append('xxx')
125 | - 注:append不能连续使用,只能一个一个append,否则报错。
126 | - 插入:listname.insert(n, '新') -- 在listname的索引n处插入新元素'新'
127 | - 删除:del语句;pop()方法;remove()方法
128 | - pop有返回值,remove没有返回值
129 | - del listname[n]:知道要删除的元素在列表中的位置时使用。删除后无法再访问它。
130 | - a = listname.pop():类似弹栈,弹出最后一个,并且返回该元素的值;弹出后仍能使用或访问这个值
131 | - a = listname.pop(n):弹出索引n对应的元素;弹出后仍能使用
132 | - listname.remove('列表中某元素'):只知道要删除元素的值,不知道索引时;移除列表中某个值的第一个匹配项;没有返回值
133 | - 列表的各种排序
134 | - 各种方式的排序:sort(); sorted(); reverse()
135 | - listname.sort():永久性排序,字母表顺序,a前z后,大写前小写后
136 | - listname.sort(reverse = True):永久性排序,字母表逆序
137 | - sorted(listname):临时性排序,字母表顺序,可赋值给变量后使用
138 | - sorted(listname, reverse = True):临时性排序,字母表逆序
139 | - listname.reverse():永久性修改,但随时可以恢复;倒着打印,注意是反转列表顺序,与字母表顺序无关
140 | - len(listname):返回列表长度,可赋值给变量后使用
141 | - 索引:
142 | - 1、索引从0开始
143 | - 2、‘-1’在任何时候都可以用来指向最后一个元素,除非列表为空才报错
144 | - 3、发生索引错误却找不到解决方法时,可将列表或其长度打印出来,可以与自己以为的截然不同
145 |
146 |
147 | - [返回目录](#目录)
148 |
149 |
150 |
151 |
152 | # 04 操作列表
153 | - [第4章笔记](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/03-%E5%88%97%E8%A1%A8%E7%AE%80%E4%BB%8B.ipynb)
154 | - [第4章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/04-%E6%93%8D%E4%BD%9C%E5%88%97%E8%A1%A8.ipynb)
155 | - 知识点:
156 | - 汇总:
157 | - for循环、缩进注意点、数值列表创建、数学统计(最值、求和)、列表解析、列表切片、元组、代码格式优化
158 | - for循环遍历:
159 | - 刚开始使用循环时请牢记,对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。
160 | - 如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次,且通常速度非常快。
161 | - 格式:for n-任意名字 in listname: 某语句
162 | - 示例:`for magician in magicians: print(magician)`
163 | - 避免缩进错误:
164 | - Python根据缩进来判断代码行与前一个代码行的关系
165 | - 常见错误:
166 | - 1-忘记缩进
167 | - 2-忘记缩进额外的代码行
168 | - 3-不必要的缩进
169 | - 4-循环后不必要的缩进
170 | - 5-遗漏冒号(python有冒号,无分号,用缩进代替大括号,注意别混淆了)
171 | - 数值列表:
172 | - range(start, stop, step):创建一个整数列表,一般用在 for 循环中
173 | - 例如:`for value in range(1,5): #生成1-4`
174 | - range():默认从0开始,默认step为1,这两个都可以省略(step优先省略),stop必须有,不包括stop本值
175 | - list(range(n)):将range()的结果直接转换为列表,可存储在变量中以后使用
176 | - 例如:`numbers = list(range(1,6))`,打印numbers结果为:[1, 2, 3, 4, 5]
177 | - 用range()创建任意数据集:新建空列表--for循环-append
178 | - 数学统计:
179 | - min(listname)-最小值;
180 | - max(listname)-最大值;
181 | - sum(listname)-求和
182 | - 列表解析:
183 | - 将 for 循环和创建新元素的代码合并成一行,并自动附加新元素。
184 | - 创建列表: `listname = [value计算或表达式 for value in range(n)]`
185 | - 代码示例:`squares = [value**2 for value in range(1,11)]`,打印结果为:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
186 | - 列表切片:
187 | - 切片:m n -- 索引值
188 | - 端点值:左闭右开,从0开始,包含第一个索引值,不包含第二个索引值。
189 | - listname[m:n] -- 从索引值m处取到索引n的前一个元素(第m-1个到第n个)
190 | - listname[:n] -- 没有指定m时,默认从列表第一个元素开始
191 | - listname[m:] -- 没有指定n时,默认取到列表的最后一个元素
192 | - listname[-m:] -- m或n为负数时,从倒数第三位取到最后一个元素
193 | - listname[:] -- 取所有元素(是全新副本不是关联,相当于复制但区别于copy deepcopy等等)
194 | - 注:浅拷贝和深拷贝涉及到改变对本体的影响。
195 | - 参考:[Python-直接赋值、浅拷贝和深度拷贝解析](https://www.cnblogs.com/anliux/p/12834845.html)
196 | - 元组:
197 | - 列表:适合存储可能变化的数据集,使用方括号标识
198 | - 考点:列表不可作为字典的key,键要求唯一、不可变
199 | - 元组:不可变的列表称为元组,使用圆括号标识
200 | - 相比列表,元组是更简单的数据结构。如需存储的一组值在程序的整个生命周期内都不变,可使用元组
201 | - 格式:tuplename = ( , , , )
202 | - 索引值从0开始,由`变量名[index]`的格式获取
203 | - 不可以修改元组的值:tuplename[n] = m -- 会报错
204 | - 虽然不可以修改元组,但是可以对存储元组的变量重新赋值
205 | - dimensions = (200,50)
206 | - dimensions[0] = 400 # 报错
207 | - dimensions = (400,50) # 顺利改变dimensions的值
208 | - 格式设置指南:
209 | - Python改进提案 (Python Enhancement Proposal,PEP)
210 | - 缩进:4个空格为一级缩进
211 | - 行长:建议每行不超过80字符
212 | - 空行:python解释器不关心但影响可读性,尽量合理
213 | - 其他
214 |
215 |
216 | - [返回目录](#目录)
217 |
218 |
219 |
220 |
221 | # 05 if语句
222 | - [第5章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/05-if%E8%AF%AD%E5%8F%A5.ipynb)
223 | - [第5章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/05-if%E8%AF%AD%E5%8F%A5.ipynb)
224 | - 知识点:
225 | - 汇总:
226 | - if语句,if-else,if-elif,多个if,各种if嵌套,
227 | - 条件测试(布尔表达式),比较数值大小,多个条件(and,or),
228 | - 检测特定值是/不包含在列表中/列表是否为空/一个列表是否在另一个列表中,
229 | - if格式(空格增加可读性)
230 | - if语句格式:
231 | - `if xxx: xxx else: xxx`
232 | - 示例:` if car == 'bmw': print(car.upper())`
233 | - 条件测试(布尔表达式)
234 | - 每条 if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试
235 | - if 条件测试(布尔表达式,就是一个为True 或者 False的表达式)
236 | - 数值大小比较:正常比较,如> >= < <=
237 | - 注:== 检查是否相等时考虑大小写,可以使用`变量名.lower()`等来消除大小写的影响。
238 | - 检查多个条件:and 或者 or组合,符合数学中的“与”和“或”的规则
239 | - 检查特定值是否包含在列表中: 'x' in list_name - 结果:True or False
240 | - 检查特定值是否不包含在列表中:关键字 not in - 'x' not in list_name - 结果:True or False,不包含时返回True
241 | - if语句结构:
242 | - if-else结构:非此即彼
243 | - if-elif-...-else结构: if嵌套
244 | - if... if... if...:测试多个条件,即不同于if-else语句,符合多个if条件时使用。
245 | - 使用if语句处理列表:
246 | - 检查特殊元素:for a in listname: if a == 'sth': (如果b列表中包含sth,就怎样)
247 | - 检查列表不是空的:if listname: ...
248 | - 检查一个列表a是否在另一个列表b中:for a in a_list: if a in b_list: ..
249 | - 设置if语句的格式:
250 | - 在诸如== 、>= 和<= 等比较运算符两边各添加一个空格,例如,if age < 4: 要比if age<4: 好
251 |
252 |
253 | - [返回目录](#目录)
254 |
255 |
256 |
257 |
258 | # 06 字典
259 | - [第6章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/06-%E5%AD%97%E5%85%B8.ipynb)
260 | - [第6章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/06-%E5%AD%97%E5%85%B8.ipynb)
261 | - 知识点:
262 | - 汇总:
263 | - 字典,键唯一值不要求,字典无序,访问,添加,修改,删除,语句过长拆分,for遍历的三种方法,字典和列表的各种相互嵌套
264 | - 一个简单的字典
265 | - 格式:dictname = {'键': '值', '键': '值', '键': '值', … '键': '值'}
266 | - 访问:dictname['键'],可赋值给变量存储后使用
267 | - 考点:
268 | - 键必须是唯一的,但值则不必。
269 | - 值可以取任何数据类型,但键必须是不可变的
270 | - 键:如字符串,数字或元组。
271 | - 值:可将python中任何对象用作字典中的值,比如数字、字符串、列表、字典等。
272 | - 使用字典:
273 | - 字典:‘键值对’,放在花括号里{},每个键都与一个值相关联,可使用键来访问与之相关联的值。
274 | - 键-值:两个相关联的值,指定键时,返回与之相关联的值;键和值冒号分隔,键-值对之间逗号分隔。
275 | - 在一个字典中,键值对的数量没有限制
276 | - 访问字典中的值:dictname['键'],返回相关联的值
277 | - 字典是无序的,而列表是有序的(可通过索引0-n进行访问,添加也是append到末尾,insert到对应位置)
278 | - 添加键值对:dictname['键'] = '值',然后就将这对键值对添加到字典中的任意位置了
279 | - 注:排列与添加顺序无关,字典是无序的
280 | - 创建空字典后添加:dictname = {} 然后 dictname['键'] = '值'....进行添加
281 | - 修改字典中的元素:dictname['键'] = '新值'
282 | - 删除字典中的元素:del dictname['键'] -- `del 字典名[键]`,就可以将该字典中的键值对删除
283 | - 过长的一行语句的拆分,如print(XXX ,+ \\ + 下一行四个空格+内容)
284 | - 遍历字典:
285 | - 遍历:for循环
286 | - 1-items()方法:所有键-值对
287 | - 2-keys()方法:所有键(可省略,加上使代码可读性更好)
288 | - 3-values()方法:所有值;
289 | - 4-set()函数:剔除重复元素
290 | - items() 方法:
291 | - 以列表形式返回可遍历的(键, 值) 元组数组(并非直接的列表,若要返回列表值还需调用list函数)
292 | - items() 方法返回值:dict_items([('last', 'fermi'), ... , ('username', 'efermi')]) -- 元组里的列表里的以键值对为单位的元组
293 | - items() + for循环:
294 | - 格式:for a, b in list.items():... 无论如何命名,a和b一前一后分别对应键和值
295 | - keys() 方法:
296 | - 返回字典中的键
297 | - keys() + for循环:
298 | - 格式:for a in dictname.keys(): ...
299 | - 提取字典dictname中的所有键,并依次将其存储到变量a中;遍历字典默认遍历键,keys()可省略
300 | - 可在for循环中对返回的键进行排序。可使用函数sorted()来获取特定顺序排列的键列表的副本
301 | - 格式:`for name in sorted(favorite_languages.keys()): xxx`
302 | - values() 方法:
303 | - 返回一个值列表,不包含任何键。
304 | - values() + for循环:
305 | - 格式:for a in dictname.values(): ... for语句提取字典中的每个值,并将它们依次存储到变量a中。
306 | - 注:字典无序,因此返回的值无序。
307 | - set()方法:
308 | - (起因:键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。)
309 | - 使用集合(set)可剔除重复项 - 类似于列表,但每个元素都是独一无二的
310 | - set():对包含重复元素的列表调用set(),可找出列表中独一无二的元素,并使用这些元素创建一个集合
311 | - 格式:for a in set(dictname.values()): ...
312 | - 注:字典无序,因此返回的值无序。
313 | - 嵌套:
314 | - 将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
315 | - 可以在列表中嵌套字典、在字典中嵌套列表、在字典中嵌套字典
316 | - 在列表中嵌套字典:
317 | - 格式:dict_1 = {} dict_2 = {} dict_3 = {} listname = [dict_1, dict_2, dict_3]
318 | - 在字典中嵌套列表:当需要在字典中将一个键关联到多个值时
319 | - 格式:dictname = {'键':'值', '键': [a, b, c, ... , m]} --- 例子中第二个键关联到a-m等多个值
320 | - 此时若用for循环遍历字典,需要两层for循环,因为键值对中的值有多个元素,因此需要for循环来遍历取出。
321 | - 在字典中嵌套字典:
322 | - 格式:dictname = { '键1': {字典1}, '键2': {字典2}, ... , '键n': {字典n} }
323 |
324 |
325 | - [返回目录](#目录)
326 |
327 |
328 |
329 |
330 | # 07 用户输入和while循环
331 | - [第7章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/07-%E7%94%A8%E6%88%B7%E8%BE%93%E5%85%A5%E5%92%8Cwhile%E5%BE%AA%E7%8E%AF.ipynb)
332 | - [第7章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/07-%E7%94%A8%E6%88%B7%E8%BE%93%E5%85%A5%E5%92%8Cwhile%E5%BE%AA%E7%8E%AF.ipynb)
333 | - 知识点:
334 | - 汇总:
335 | - input(),求模运算%,
336 | - while循环,标志(封装的布尔表达式),break退出循环,
337 | - while循环处理字典和列表(列表间移动元素、删除列表中多次出现的元素、input填充字典)
338 | - 函数input()的工作原理:
339 | - 让程序暂停运行,等待用户输入一些文本。获取用户输入后,将其存储在一个变量中。回车继续运行。
340 | - input(参数):暂停程序,展示括号中的参数,等待用户输入,回车继续运行,并返回输入的值
341 | - 例如:`message = input('Tell me something, and I will repeat it back to you: ')`
342 | - input():默认返回值是字符串,可用int()将str转为数值型,可将存储input返回值的变量放在int()中,或直接int(input())
343 | - 求模运算符:
344 | - % :将两数相除并返回余数
345 | - 格式:m % n
346 | - while循环概述:
347 | - for循环:用于针对集合中的每个元素都一个代码块
348 | - while循环:不断运行,直到指定的条件不满足为止
349 | - while循环格式:while 语句: xxx xxx .. xx(可内含多条语句)
350 | - 标志:定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为‘标志’
351 | - 标志的好处:while只需检查标志一个条件,并将所有测试 (是否发生了应将标志设置为False的事件) 都放在其他地方,使程序更为整洁
352 | - 代码示例:`active = True \\ while active: \\ message = input(prompt) \\ if message == 'quit': active = False`
353 | - break退出循环:立即退出循环,不再运行循环中余下的代码,也不管条件测试的结果如何
354 | - break循环:可以用在任何Python循环中,例如,退出遍历列表或字典的for循环
355 | - continue:
356 | - 在循环中使用continue:返回到循环开头,并根据条件测试结果决定是否继续执行循环
357 | - 场景:当符合某if条件时,直接结束本次循环并跳到下一次循环的判断阶段,即跳过continue后的语句。
358 | - 使用while循环来处理列表和字典:
359 | - 在列表之间移动元素:
360 | - 示例:while list_1: a = list_1.pop() list_2.append(a) --- 可将list_1中的元素逐渐移动到list_2中
361 | - 删除一个列表中多次出现的元素:
362 | - 示例:while 'xx' in listname: listname.remove('xx')
363 | - 代码示例:`while 'cat' in pets: \\ pets.remove('cat')`
364 | - 使用用户输入填充字典:
365 | - 创建空字典 \\ 标志=True \\ while 标志: xx xxx xx input \\ if xx: 标志 = False
366 |
367 |
368 | - [返回目录](#目录)
369 |
370 |
371 |
372 |
373 | # 08 函数
374 | - [第8章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/08-%E5%87%BD%E6%95%B0.ipynb)
375 | - [第8章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/08-%E5%87%BD%E6%95%B0.ipynb)
376 | - 知识点:
377 | - 汇总:
378 | - 函数定义,函数调用(位置实参,关键字实参),形参默认值,等效的函数调用(多种方法),避免实参错误(数量等),
379 | - 返回值(封装功能、使用默认值来让调用实参可选、返回字典列表等对象,与while循环等结构结合),
380 | - 传递列表(在函数中修改列表、切片获取列表副本以保留原列表),
381 | - 传递任意数量实参(与位置实参、关键字实参结合、一个星号任意数量,两个星号空字典),
382 | - 模块导入(导入整个模块、特定函数、as指定模块或函数名、导入模块中所有函数),函数编写规则
383 | - 定义函数的格式:
384 | - def 函数名(参数,有无均可): xx xx ... xx
385 | - 传递实参:
386 | - 1-位置实参:要求实参的顺序与形参的顺序相同
387 | - 2-关键字实参:每个实参都由变量名和值组成
388 | - 其他:还可使用列表和字典等...
389 | - 主要针对调用函数时,实参的写法:
390 | - 位置实参:基于实参的顺序,根据位置对应函数定义中的各个形参
391 | - 代码示例:`describe_pet('hamster', 'harry')`
392 | - 关键字实参:传递给函数的名称-值对,直接在实参中将名称和值关联起来,因此不会混淆,无需考虑位置
393 | - 代码示例:`describe_pet(animal_type='hamster', pet_name='harry')`
394 | - 形参默认值:
395 | - 调用函数中提供实参时,使用指定实参值;否则,使用形参的默认值
396 | - 调用:可任选位置实参或关键字实参;形参默认值可简化函数的调用
397 | - 注意:若使用默认值,函数定义时,形参列表先列出没有默认值的,再列出有默认值的,以便正确地解读位置实参
398 | - 形参的顺序是先名字后类型,因此当只包含一个实参,依然会被视为位置实参;也可以使用关键字实参。
399 | - 代码示例:`def describe_pet(pet_name, animal_type='dog')`
400 | - 等效的函数调用:
401 | - 即:使用不同的传参方式,得到相同的结果。
402 | - 可混合使用位置实参、关键字实参、默认值等。
403 | - 避免实参错误:
404 | - 当提供的实参多于或少于函数完成其工作所需的信息时,将出现实参不匹配错误 - 会报错
405 | - 学会读错误提示,并从源程序中找出错误之处
406 | - 返回值
407 | - 返回值的作用:将繁杂的工作封装到函数,从而简化主程序
408 | - 格式:a = xxxxxxxx return a
409 | - 使用默认值来让实参变成可选的,使函数调用时,只在必要时才提供额外的信息
410 | - 代码示例:`def get_formatted_name(first_name, last_name, middle_name=''): `
411 | - 针对有无中间名的情况,在函数中进行判定,`if middle_name: \\ full_name = .. \\ else ... `
412 | - 可选值让函数能够处理各种不同情形的同时,确保函数调用尽可能简单
413 | - 函数可返回任何类型的值,包括列表和字典等较复杂的数据结构
414 | - 格式:z = {} / [] / ... (任意类型,列表、字典等) return a
415 | - 可将函数同任何Python结构结合起来使用:while,if等等
416 | - 如下while嵌套if语句感觉很巧妙
417 | - 格式:while True: xxx if input = q break..... if input = q break..
418 | - 传递列表:
419 | - 可将列表等对象作为实参传递给函数
420 | - 向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)
421 | - 在函数中修改列表:
422 | - 比如把一个列表中的元素移动到另一个列表,并做一些其他修改,封装在函数中
423 | - 依然是pop()和append()
424 | - 禁止函数修改列表:
425 | - 思路--调用函数时,向函数传递列表的副本而不是原件,这样函数所做的任何修改都只影响副本,而可保留原件
426 | - 要将列表的副本传递给函数:
427 | - 切片法 -- 格式:function_name(list_name[:])
428 | - 代码示例:`print_models(unprinted_designs[:], completed_models)`
429 | - 传递任意数量实参:
430 | - 格式:形参写为"星号+参数名"
431 | - 例如:`*paraname`,则不管调用语句提供多少实参,这个形参都将它们收入囊中
432 | - 代码示例:
433 | - `def make_pizza(*toppings): xxx`
434 | - `make_pizza('mushrooms','green peppers','extra cheese')`
435 | - 位置实参+任意数量实参:
436 | - 任意数量实参的形参放在最后:先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中
437 | - 代码示例:
438 | - `def make_pizza(size, *toppings):`
439 | - `make_pizza(12, 'mushrooms','green peppers','extra cheese')`
440 | - 任意数量的关键字实参:
441 | - 任意数量且预先不知道信息类型,将函数编写成能够接受任意数量的 '键-值' 对 - 调用语句提供了多少就接受多少
442 | - 格式:形参`**dictname` -- 两个星号创建一个空字典,并用for循环将 键值对 封装到这个字典中
443 | - 代码示例:
444 | - `def build_profile(first, last, **user_info):`
445 | - `user_profile = build_profile('albert', 'einstein',location='princeton', field='physics')`
446 | - 将函数存储在模块中:
447 | - 模块:将函数封装在独立的 `*.py` 文件中,使用时,import到主程序中。模块,即独立的py文件
448 | - 导入整个模块:
449 | - 导入格式:import modulename -- eg:`import pizza`
450 | - 调用格式:module_name.function_name() -- eg:`pizza.make_pizza(16, 'pepperoni')`
451 | - 导入特定函数:
452 | - 导入格式:from module_name import function_name
453 | - 调用格式:function_name()
454 | - 导入任意数量的函数,逗号分隔函数名
455 | - 导入格式:from module_name import function_0, function_1, function_2
456 | - 调用格式:function_name()
457 | - 使用as给函数指定别名:
458 | - 导入格式:from module_name import function_name as fn
459 | - 调用格式:fn()
460 | - 使用as给模块指定别名:
461 | - 导入格式:import module_name as mn
462 | - 调用格式:mn.function_name()
463 | - 导入模块中的所有函数:
464 | - 导入格式:from module_name import *
465 | - 调用格式:function_name()
466 | - 如果模块中有函数的名称与你的项目中使用的名称相同,可能覆盖,而不是分别导入所有的函数 使用并非自己编写的大型模块时,最好不要采用这种导入方法: (此处只介绍方法,方便在阅读代码时知道在做什么,但自己写代码时不建议使用)
467 | - 小结:直接导入模块(py文件名)时,调用要写模块名;导入模块中的具体功能时,调用时直接使用功能名。
468 | - 函数编写指南:
469 | - 1-函数名:描述性,且只使用小写字母和下划线(模块名同)
470 | - 2-注释:紧跟在定义后,简要阐述功能,并采用文档字符串格式(三引号)
471 | - 3-形参指定默认值时,等号两边不要有空格
472 | - 4-函数调用中的关键字实参,等号使用同上一条
473 | - 5-每一行长度不超过79字符
474 | - 形参很多,导致函数定义长度超过时,在函数定义中输入左括号,回车,
475 | - 并在下一行按两次Tab键,将形参列表和只缩进一层的函数体区分开
476 | - 6-程序包含多个函数时,可使用两个空行将相邻的函数分开,这样更容易看清楚¶
477 | - 7-所有的import语句都应放在文件开头,唯一例外的情形是,在文件开头使用注释来描述整个程序时
478 |
479 |
480 | - [返回目录](#目录)
481 |
482 |
483 |
484 |
485 | # 09 类
486 | - [第9章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/09-%E7%B1%BB.ipynb)
487 | - [第9章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/09-%E7%B1%BB.ipynb)
488 | - 知识点:
489 | - 汇总:
490 | - 类名首字母大写,方法(类中的函数),init(),self,创建实例,命名规则,
491 | - 访问属性和调用方法(句点表示法),创建多个实例,
492 | - 类中的每个属性都必须有初始值,有默认值的属性没有形参,修改属性的值的三种方法:实例修改;方法修改;方法递增,
493 | - 继承(super,super().__ init __(xx,xx),子类的调用),将实例作为类的属性及其调用,调用作为子类的属性之一的xx类的实例,
494 | - 导入类(一个模块中存储一个或多个类,导入单个类或多个类,导入整个模块,导入模块中的所有类,在一个模块中导入另一个模块类似嵌套),
495 | - Python标准库,类编码风格
496 | - 创建和使用类:
497 | - 使用类几乎可以模拟任何东西,之后可用类来创建特定的实例
498 | - 命名规则:Python中首字母大写的名称是类
499 | - 方法:类中的函数。与上一章函数的区别是,调用的方式
500 | - init():一个特殊的方法,每当根据类创建新实例时,都会自动运行,首尾各两个下划线,避免默认的方法与普通方法名称冲突
501 | - 格式示例:`def __init__(self, name, age): xxx \\ self.name = name \\ self.age = age`
502 | - self:自动传递,因此只需要给除了self之外的其他形参提供值
503 | - init()下的self.xx为属性值的初始化
504 | - 以self为前缀的变量都可供类中的所有方法使用,还可通过类的任何实例来访问这些变量,像这样可通过实例访问的变量称为属性
505 | - 根据类创建实例:
506 | - 可将类视为有关如何创建实例的说明
507 | - `class Dog(): def __init__(self, name, age):`
508 | - `my_dog = Dog('willie', 6)`
509 | - 使用实参调用类中的方法init(),并未显式地return但默认返回一个实例,并存储在自定义的变量中
510 | - 命名规则:
511 | - 首字母大写(Dog)默认指类,小写默认指根据类创建的实例(my_dog)
512 | - 访问属性:
513 | - 句点表示法 eg:my_dog.name
514 | - 调用方法:
515 | - 句点表示法 eg:my_dog.sit()
516 | - 创建多个实例:
517 | - 每个实例都是独立的个体,拥有自己的一组属性,即使属性相同。
518 | - 可按需根据一个类创建任意数量的实例,条件是将每个实例都存储在不同的变量中,或占用列表或字典的不同位置
519 | - 使用类和实例
520 | - 类中的每个属性都必须有初始值,哪怕这个值是0或空字符
521 | - 有默认值的属性没有形参:如设置默认值,可在方法init()内指定这种初始值。并且在定义括号中无需包含为它提供初始值的形参
522 | - eg: 在init()中定义默认值 self.odometer_reading = 0,则def行无需包含odometer_reading这个形参
523 | - 修改属性的值:
524 | - 三种方法:直接通过实例修改;通过方法进行设置;通过方法进行递增(增加特定的值)
525 | - 法一:直接修改属性的值
526 | - 通过实例直接访问它,使用句点表示法直接访问并设置汽车的属性odometer_reading
527 | - eg:my_new_car.odometer_reading = 23
528 | - 法二:通过方法修改属性的值
529 | - 定义更新属性的方法,则无需直接访问属性,而将值传递给一个方法,由它在内部进行更新
530 | - eg:def update_odometer(self, mileage):xxxxx 调用:my_new_car.update_odometer(45)
531 | - 法三:通过方法对属性的值进行递增,与法二类似
532 | - eg:def increment_odometer(self,miles): self.odometer_reading += miles
533 | - """将里程表读数增加指定的量"""
534 | - 调用:my_used_car.increment_odometer(100) --- 将里程表数值在原有基础上增加100(100是实参)
535 | - 继承
536 | - 原有的类-父类;新类-子类
537 | - 子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法
538 | - 创建子类:
539 | - 创建子类时,父类必须包含在当前文件中,且位于子类前面
540 | - 创建子类的实例时,首先需要给父类的所有属性赋值
541 | - 定义子类时,必须在括号内指定父类的名称
542 | - 示例:`class ElectricCar(Car):`
543 | - super():一个特殊函数,帮助将父类和子类关联起来。
544 | - 父类也称为超类(superclass),名称super由此得名
545 | - super(). __ init __ (xx, xx, xx)
546 | - 这行代码位于子类的init()下,调用父类方法init(),xx是父类形参,让子类实例包含父类的所有属性
547 | - 在子类中除init外,可def子类特有的方法,也可以重写父类已有、但子类要求功能不同的方法(父类已有且相同的不再赘述)
548 | - 示例:`self.battery_size = 70` 功能重写略
549 | - 子类调用:
550 | - abc.function_name() -- 这个function可以是父类的,也可以是子类的
551 | - 将实例用作属性:
552 | - 将类的一部分作为一个独立的类提取出来
553 | - eg:battery属性功能很多,故独立放到另一个类Battery中,并将一个Battery实例用作ElectricCar类的一个属性(最后一句关键)
554 | - 将实例用作属性的定义类:
555 | - def Car() \\ def Battery() \\ def ElectricCar(Car) \\
556 | - 其中ElectricCar类中的init部分,除了继承父类的super().__init__(xx,xx,xx..)外,还要有一句:
557 | - self.battery = Battery() -- 创建一个新的Battery实例,并存储在属性self.battery中
558 | - 此时,每当子类的__init__()方法被调用时,都将执行该操作。
559 | - 因此现在每个ElectricCar实例都包含一个自己创建的Battery实例
560 | - 调用作为子类的属性之一的Battery类的实例:
561 | - my_tesla.battery.describe_battery(),my_tesla存储实例
562 | - 这行代码在实例my_tesla中查找属性battery,并对储存在该属性中的Batter实例调用方法describe_battery()
563 | - battery在ElectricCar的init中初始化了
564 | - 故这里可以作为实例的一个属性使用,并且更深入地调用Battery中的功能describe_battery()
565 | - 导入类
566 | - Python允许你将类存储在模块中,然后在主程序中导入所需的模块
567 | - 注:第8章导入是将函数存储在模块中,from filename import xx_function,导入函数,而这里是import class
568 | - 设独立文件中的某模块:module_name.py ---- 内含多个类 Class_1, Class_2, .. , Class_n
569 | - 导入单个类:
570 | - from module_name import Class_1
571 | - 在一个模块中存储多个类,并导入其中一个:from module_name import Class_i
572 | - 从一个模块中导入多个类:from module_name import Class_1, Class_2, Class_n
573 | - 创建实例并调用:a = Class_i() \\ a.function_j()....
574 | - 直接Class创建;直接function调用,不用带类名
575 | - 导入整个模块:import module_name
576 | - 创建实例并调用:a = module_name.Class_i() \\ a.function_i()....
577 | - 创建声明模块名和类名;直接function调用,不用带类名
578 | - 导入模块中的所有类:from module_name import * (和所有函数的区别是什么..)
579 | - 不推荐星号import,如需从一个模块中导入很多类,最好导入整个模块,并使用 module_name.Class_name来访问类
580 | - 在一个模块中导入另一个模块:当有import关系的类分布在不同文件中时
581 | - 创建实例并调用:直接Class创建;直接function调用,不用带类名
582 | - module_1.py: Class_1 module_2.py: from module_1 import Class_1 Class_2
583 | - a = Class_1() b = Class_2()
584 | - a.function_1() b.function_2()
585 | - 注:只有导入整个模块时需要在创建时声明模块名和类名,其他情况都是只声明类名;调用都是直接function调用,不用带类名
586 | - Python标准库
587 | - 类编码风格:
588 | - 你必须熟悉有些与类相关的编码风格问题,在你编写的程序较复杂时尤其如此。
589 | - 类名应采用驼峰命名法 ,即将类名中的每个单词的首字母都大写,而不使用下划线。
590 | - 实例名和模块名都采用小写格式,并在单词之间加上下划线。
591 | - 对于每个类,都应紧跟在类定义后面包含一个文档字符串。这种文档字符串简要地描述类的功能,并遵循编写函数的文档字符串时采用的格式约定。 每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述。
592 | - 可使用空行来组织代码,但不要滥用。 在类中,可使用一个空行来分隔方法;而在模块中,可使用两个空行来分隔类。
593 | - 需要同时导入标准库中的模块和你编写的模块时,先编写导入标准库模块的import 语句,再添加一个空行,然后编写导入你自己编写的模块的import 语句。 在包含多条import 语句的程序中,这种做法让人更容易明白程序使用的各个模块都来自何方。
594 |
595 |
596 | - [返回目录](#目录)
597 |
598 |
599 |
600 |
601 | # 10 文件和异常
602 | - [第10章笔记](https://github.com/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/10-%E6%96%87%E4%BB%B6%E5%92%8C%E5%BC%82%E5%B8%B8.ipynb)
603 | - [第10章笔记-备用链接](https://nbviewer.jupyter.org/github/anliux/Python-Crash-Course/blob/master/src/PartI_Basics/10-%E6%96%87%E4%BB%B6%E5%92%8C%E5%BC%82%E5%B8%B8.ipynb)
604 | - 知识点:
605 | - 汇总:
606 | - open()打开文件并返回文件对象、绝对路径和相对路径、不同系统中路径的斜杠或反斜杠、
607 | - with关键字与close()、read()读取文件并返回字符串、strip()删除空格、逐行读取、readline()、readliens()、
608 | - 读取文本文件默认为字符串若需要数字需转换、open(filename,'w')、
609 | - 模式实参、写入模式注意覆盖、只能将字符串写入文本文件(必要时str转换)、写入多行(write()语句中添加换行、制表符、空格等)、
610 | - 附加模式'a'(不覆盖原有内容,将新写入添加到末尾)、指定文件名不存在时自动新建并写入、
611 | - try-except-else代码块(格式、功能等)、split()方法、pass语句(什么都不做语句)、
612 | - JSON文件的写入和读取(json.dump()和json.load())、及时考虑错误处理(读取文件时考虑FileNotFoundError等可能的错误)、
613 | - 代码重构
614 | - 从文件中读取数据的常用功能:
615 | - rstrip()方法:删除字符串末尾多余的空行(如10.1.1)
616 | - strip()方法:删除字符串两边的空格(如10.1.5)
617 | - readline()-读取每个字符;
618 | - readlines()-读取每一行 ---- 一般用在for循环中(如10.1.4)
619 | - 读取整个文件:
620 | - 示例:`with open('pi_digits.txt') as file_object:`
621 | - 函数open():传入要打开的文件的名称,返回一个‘表示文件的对象’,并存储在指定变量中(file_object)
622 | - open()之后Python会在当前执行的文件所在的目录找那个查找指定的文件
623 | - open()是默认打开当前文件夹下的文件,否则需要提供文件路径
624 | - 示例续:`contents = file_object.read()
625 | - 前面拿到文件对象后,这一步使用方法read()读取这个文件的全部内容,并将其作为一个‘长字符串’存储在变量中`
626 | - 不同系统中路径的斜杠和反斜杠:
627 | - Windows系统中,在文件路径中使用反斜杠( \ )而不是斜杠( / )
628 | - 当前文件夹下文件打开:
629 | - 格式:with open('filename.txt') as file_object:xxx
630 | - 非当前文件夹下文件打开:
631 | - 相对路径和绝对路径
632 | - 绝对路径和相对路径:
633 | - 绝对路径:程序在电脑中的完整路径那种路径
634 | - 相对路径:在当前py程序文件目录下有的文件夹路径,可以直接省略程序文件所在,直接写文件夹名字+文件名
635 | - 相对路径:省略程序所在路径的部分(绝对路径中前面的部分可以省略)
636 | - 格式:with open('text_files\filename.txt') as file_object:
637 | - 打开的是程序所在路径下的text_files的文件夹,名为filename.txt的文件时
638 | - 绝对路径:提供完整的路径。注意win系统中使用反斜杠,linux和OS X中使用斜杠
639 | - 格式:绝对路径内容太长可单独存放在变量中先。
640 | - 首先将路径单独存放在变量中:`file_path = '/home/ehmatthes/other_files/text_files/filename.txt' `
641 | - with打开文件时,将路径变量传入:`with open(file_path) as file_object: xxx`
642 | - 关键字with:在不再需要访问文件后将其关闭。
643 | - 若手动使用close()关闭,可能存在过早或过晚关闭文件导致的错误,用with结构则不存在这样的问题
644 | - 读取文件
645 | - 格式:abc = file_object.read()
646 | - open拿到文件对象后,使用方法read()读取这个文件的全部内容,并作为一个‘长字符串’存储在变量abc中
647 | - rstrip()方法:删除字符串末尾多余的空行
648 | - strip()方法:删除字符串两边的空格(没记错的话应该是这样,lstrip()是删除左边的空格)
649 | - 逐行读取:for循环+line方法(rstrip配合食用)
650 | - 格式:for line in file_object: # file_object
651 | - 注:for line in listname: xxx -- 这里listname是按行的,for语句默认逐行读取了,略迷
652 | - 将读取到的各行存储在列表中:
653 | - with关键字:open()返回的文件对象只在with代码块内可用
654 | - 如想在with代码块外访问文件内容,可在with代码块内将文件的各行存储在一个列表中
655 | - 代码示例:
656 | - with open(filename) as file_object:
657 | - lines = file_object.readlines() # 读取每一行并存储在变量lines中作为一个列表
658 | - readline() - 读取单个字符,readlines() - 读取每一行
659 | - 注:读取文本文件时,将其中所有文本都默认为字符串。可按需使用int()或float()将其转换为数字
660 | - 生日在pi中小代码片段
661 | - 写入文件:write()方法:写入
662 | - 写入格式:with open(filename,'w') as file_object: file_object.write('xxxxx.')
663 | - open的第一个实参是要打开的文件的名称;第二个实参表示打开这个文件所用的模式
664 | - 模式实参:读取模式'r',写入模式'w',附加模式'a',读取+写入模式'r+'
665 | - 省略了模式实参时,将以默认的只读模式打开文件
666 | - 当要写入的文件不存在时,函数open()将自动创建它
667 | - w模式要小心:如果指定文件已存在,在返回文件对象前清空(覆盖??)该文件
668 | - 只能将字符串写入文本文件中。
669 | - 若要将数值数据存储到文本文件中,必须先使用str()将其转换为字符串
670 | - 写入多行:
671 | - write()不会在写入的文本末尾添加换行符,需要在语句中包含换行符、制表符、空格等
672 | - 附加到文件:
673 | - 用附加模式'a'打开文件:写入到文件的行都将添加到文件末尾。
674 | - 如果指定的文件不存在,将创建一个空文件
675 | - 异常
676 | - 异常概述:
677 | - 当发生让Python不知所措的错误时,它都会创建一个异常对象。
678 | - 如果你编写了处理该异常的代码,程序将继续运行。
679 | - 否则,程序将停止,并显示一个traceback,其中包含有关异常的报告
680 | - try-except-else代码块:
681 | - 出现异常,程序也将继续运行,并显示编写好的友好的错误信息。
682 | - try-except-else代码块:类似于if-else代码块,可帮助程序友好、安全地执行
683 | - 安全:将可能发生错误的除法部分放到try-except代码块中,防止恶意崩坏
684 | - 格式:try: xxx except xxxError: yyy else: zzz
685 | - 尝试执行xxx:如果xxx错误,则yyy;否则,zzz
686 | - try顺序执行:
687 | - 如果出现except错误,执行except语句;
688 | - 如果没有出现except错误,跳过except部分,继续执行(若有else,执行else语句);
689 | - try必执行,except相当于if xx,else可省略
690 | - split()方法:根据一个字符串,按照空格创建一个单词列表
691 | - split()方法:将字符串按照空格划分,创建为单词列表(字符列表)(没有空格按一个单词创建)
692 | - 格式:a = strname.split() -- 根据strname中的字符串生成单词列表
693 | - 多个文件:def封装功能并配合for循环食用
694 | - pass语句:可在代码块中使用来让Python什么都不要做
695 | eg:except xxxError: pass
696 | 则预设错误出现时,什么都不做,继续执行程序的其他部分
697 | 凭借经验可判断该在程序的什么地方包含异常处理块,以及出现错误时该向用户提供多少相关的信息
698 | - 存储数据
699 | - JSON:一种在程序之间共享数据的简单方式
700 | - JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,随后成了一种常见格式,被包括Python在内的众多语言采用。
701 | - 使用前需要导入json模块:import json
702 | - json的写入和读取:json.dump()--写入;json.load()--读取
703 | - 注:菜鸟教程里的是复数,括号里的参数也很多设置dumps,loads
704 | - 写入格式:
705 | - `with open(filename, 'w') as f_obj: # 以写入模式打开这个文件。若文件不存在,将新建这个文件`
706 | - `json.dump(listname, f_obj) # 使用函数json.dump()将列表listname存储到文件numbers.json中`
707 | - 读取格式:
708 | - `with open(filename) as f_obj:`
709 | - `a = json.load(f_obj) # 将读取到的json文件内容存储到变量a中`
710 | - open()--如果文件不存在,读取模式不会创建新文件会报错,写入模式会创建新文件
711 | - 为保护程序,需要将FileNotFoundError写入try-except代码块中
712 | - 具体:try-读取文件,except-FileNotFoundError:以写入模式读取。
713 | - 重构:
714 | - 多个功能时,可重构,将不同功能def封装到单个函数中
715 |
716 |
717 | - [返回目录](#目录)
718 |
719 |
720 |
721 |
722 | # 11 测试代码
723 | (注:各种报错,待整理)
724 | - [第11章笔记]()
725 |
726 |
727 | - [返回目录](#目录)
728 |
729 |
730 |
731 |
732 | ### END
733 |
--------------------------------------------------------------------------------
/src/PartI_Basics/car.py:
--------------------------------------------------------------------------------
1 | # 第9章 9.4.1 导入单个类
2 |
3 | class Car():
4 | """一次模拟汽车的简单尝试"""
5 |
6 | def __init__(self, make, model, year):
7 | """初始化描述汽车的属性"""
8 | self.make = make
9 | self.model = model
10 | self.year = year
11 | self.odometer_reading = 0
12 |
13 | def get_descriptive_name(self):
14 | """返回整洁的描述性名称"""
15 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model
16 | return long_name.title()
17 |
18 | def read_odometer(self):
19 | """打印一条消息,指出汽车的里程"""
20 | print('This car has ' + str(self.odometer_reading) + ' miles on it.')
21 |
22 | def update_odometer(self, mileage):
23 | """
24 | 将里程表读数设置为指定的值
25 | 拒绝将里程表往回拨
26 | """
27 | if mileage >= self.odometer_reading:
28 | self.odometer_reading = mileage
29 | else:
30 | print("You can't roll back an odometer!")
31 |
32 | def increment_odometer(self, miles):
33 | """将里程表读数增加指定的量"""
34 |
35 | # 在editplus里编辑空格之类的,import竟然失败,说是空格不对,复制到jupyter里一看空格果然不对劲。。不知道为啥
36 |
37 |
38 |
39 | # 9.4.2 - 在一个模块中存储多个类:加入类Battery和ElectricCar
40 | class Battery():
41 | """一个模拟电动汽车的简单尝试"""
42 |
43 | def __init__(self, battery_size=70):
44 | """初始化电瓶的属性"""
45 | self.battery_size = battery_size
46 |
47 | def describe_battery(self):
48 | """打印一条描述电瓶容量的消息"""
49 | print("This car has a " + str(self.battery_size) + '-kWh battery.')
50 |
51 | # 给电池类新加一个功能,而不会搞乱各种东西
52 | def get_range(self):
53 | """打印一条消息,指出电瓶的续航里程"""
54 | if self.battery_size == 70:
55 | range = 240
56 | elif self.battery_size == 85:
57 | range = 270
58 |
59 | message = "This car can go approximately " + str(range)
60 | message += " miles on a full charge."
61 | print(message)
62 |
63 |
64 | class ElectricCar(Car):
65 | """电动汽车的独特之处"""
66 |
67 | def __init__(self, make, model, year):
68 | """
69 | 初始化父类的属性,再初始化电动汽车特有的属性
70 | """
71 | super().__init__(make,model,year)
72 | self.battery = Battery()
73 |
--------------------------------------------------------------------------------
/src/PartI_Basics/dataframe.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anliux/Python-Crash-Course/6f56d8f46f17840898ab66b76a55c2b8ba29cd2c/src/PartI_Basics/dataframe.xlsx
--------------------------------------------------------------------------------
/src/PartI_Basics/df2.csv:
--------------------------------------------------------------------------------
1 | ,col1,col2,col3,col4
2 | 0,1,4,7,1
3 | 1,2,5,8,1
4 | 2,3,6,9,1
5 | 3,4,7,0,1
6 |
--------------------------------------------------------------------------------
/src/PartI_Basics/name_function.py:
--------------------------------------------------------------------------------
1 | # name_function.py 最终的样子
2 | def get_formatted_name(first, last, middle=''):
3 | # 改为可妥善处理中间名的,即当没有中间名时也不会报错
4 | if middle:
5 | full_name = first + ' ' + middle + ' ' + last
6 | else:
7 | full_name = first + ' ' + last
8 | return full_name.title()
--------------------------------------------------------------------------------
/src/PartI_Basics/numbers.json:
--------------------------------------------------------------------------------
1 | [2, 3, 5, 7, 11, 13]
--------------------------------------------------------------------------------
/src/PartI_Basics/pi_digits.txt:
--------------------------------------------------------------------------------
1 | 3.1415926535
2 | 8979323846
3 | 2643383279
--------------------------------------------------------------------------------
/src/PartI_Basics/pizza.py:
--------------------------------------------------------------------------------
1 | # 8.6章 - import测试
2 |
3 | # pizza.py
4 | # 包含模块make_pizza
5 |
6 | def make_pizza(size, *toppings):
7 | """概述要制作的比萨"""
8 | print('\nMaking a ' + str(size) +
9 | '-inch pizza with the following toppings:')
10 | for topping in toppings:
11 | print('- ' + topping)
--------------------------------------------------------------------------------
/src/PartI_Basics/programming.txt:
--------------------------------------------------------------------------------
1 | I love programming.
2 | I love creating new games.
3 | I also love finding meaning in large datasets.
4 | I love creating apps that can run in a browser.
5 | I also love finding meaning in large datasets.
6 | I love creating apps that can run in a browser.
7 |
--------------------------------------------------------------------------------
/src/PartI_Basics/survey.py:
--------------------------------------------------------------------------------
1 | class AnonymousSurvey():
2 | """Collect anonymous answers to a survey question."""
3 |
4 | def __init__(self, question):
5 | """Store a question, and prepare to store responses."""
6 | self.question = question
7 | self.responses = []
8 |
9 | def show_question(self):
10 | """Show the survey question."""
11 | print(self.question)
12 |
13 | def store_response(self, new_response):
14 | """Store a single response to the survey."""
15 | self.responses.append(new_response)
16 |
17 | def show_results(self):
18 | """Show all the responses that have been given."""
19 | print("Survey results:")
20 | for response in self.responses:
21 | print('- ' + response)
--------------------------------------------------------------------------------
/src/PartI_Basics/test_94.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 13,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "name": "stdout",
10 | "output_type": "stream",
11 | "text": [
12 | "2016 Tesla Model S\n",
13 | "This car has a 70-kWh battery.\n",
14 | "This car can go approximately 240 miles on a full charge.\n"
15 | ]
16 | }
17 | ],
18 | "source": [
19 | "# 9.4.2-在一个模块中存储多个类\n",
20 | "\n",
21 | "# 可根据需要在一个模块中存储任意数量的类\n",
22 | "# 类Battery和ElectricCar都可以帮助模拟汽车,可加入car.py中\n",
23 | "\n",
24 | "\n",
25 | "\n",
26 | "\n",
27 | "# my_electric_car.py\n",
28 | "from car import ElectricCar\n",
29 | "\n",
30 | "my_tesla = ElectricCar('tesla','model s',2016)\n",
31 | "\n",
32 | "print(my_tesla.get_descriptive_name())\n",
33 | "my_tesla.battery.describe_battery()\n",
34 | "my_tesla.battery.get_range()"
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": 14,
40 | "metadata": {},
41 | "outputs": [
42 | {
43 | "name": "stdout",
44 | "output_type": "stream",
45 | "text": [
46 | "2016 Volkswagen Beetle\n",
47 | "2016 Tesla Roadster\n"
48 | ]
49 | }
50 | ],
51 | "source": [
52 | "# 9.4.3-从一个模块中导入多个类\n",
53 | "\n",
54 | "\n",
55 | "# 如果要在同一个程序中创建普通汽车和电动汽车,就需要将Car和ElectricCar类都导入\n",
56 | "\n",
57 | "# my_cars.py\n",
58 | "\n",
59 | "from car import Car, ElectricCar\n",
60 | "my_beetle = Car('volkswagen','beetle',2016)\n",
61 | "print(my_beetle.get_descriptive_name())\n",
62 | "\n",
63 | "my_tesla = ElectricCar('tesla','roadster',2016)\n",
64 | "print(my_tesla.get_descriptive_name())"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 17,
70 | "metadata": {},
71 | "outputs": [
72 | {
73 | "name": "stdout",
74 | "output_type": "stream",
75 | "text": [
76 | "2016 Volkswagen Beetle\n",
77 | ">\n"
78 | ]
79 | }
80 | ],
81 | "source": [
82 | "# 9.4.4-导入整个模块\n",
83 | "\n",
84 | "# 导入整个car模块,并创建一辆普通汽车和一辆电动汽车\n",
85 | "# my_cars.py\n",
86 | "\n",
87 | "# 格式:module_name.class_name 访问需要的类\n",
88 | "\n",
89 | "import car\n",
90 | "my_beetle = car.Car('volkswagen','beetle',2016)\n",
91 | "print(my_beetle.get_descriptive_name())\n",
92 | "\n",
93 | "my_tesla = car.ElectricCar('tesla','roadster',2016)\n",
94 | "print(my_tesla.get_descriptive_name)"
95 | ]
96 | }
97 | ],
98 | "metadata": {
99 | "kernelspec": {
100 | "display_name": "Python 3",
101 | "language": "python",
102 | "name": "python3"
103 | },
104 | "language_info": {
105 | "codemirror_mode": {
106 | "name": "ipython",
107 | "version": 3
108 | },
109 | "file_extension": ".py",
110 | "mimetype": "text/x-python",
111 | "name": "python",
112 | "nbconvert_exporter": "python",
113 | "pygments_lexer": "ipython3",
114 | "version": "3.5.6"
115 | }
116 | },
117 | "nbformat": 4,
118 | "nbformat_minor": 2
119 | }
120 |
--------------------------------------------------------------------------------
/src/PartI_Basics/username.json:
--------------------------------------------------------------------------------
1 | "Adam"
--------------------------------------------------------------------------------
/src/PartI_Basics/usernames.json:
--------------------------------------------------------------------------------
1 | "Alice"
--------------------------------------------------------------------------------