笨方法学Python3(21-44)
相关代码详见github地址:https://github.com/BMDACMER/Learn-Python
接着前天的总结
习题21:函数可以返回某些东西
定义函数的加减乘除,以及嵌套使用
习题22:回顾以前学的知识
习题23:字符串、字节串和字符编码
综合运用字符串、函数、文件读取等知识。详情如下:
- from sys import argv
- script, encoding, error = argv # 命令行参数处理
- def main(language_file, encoding,errors):
- line = language_file.readline() # 就是用readline()处理文本
- if line: # 防止函数永远循环下去
- print_line(line, encoding, errors)
- return main(language_file, encoding, errors)
- def print_line(line, encoding, errors): # 对languages.txt中的每一行进行编码
- next_lang = line.strip() # 移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
- raw_bytes = next_lang.encode(encoding,errors = errors)
- cooked_string = raw_bytes.decode(encoding, errors = errors)
- print(raw_bytes, "<===>",cooked_string)
- languages = open("language.txt",encoding = "utf-8")
- main(languages, encoding, error)
习题24: 更多的练习
部分代码如下:
- start_point = start_point / 10
- print("We can also do that this way:")
- formula = secret_formula(start_point)
- # this is an easy way to apply a list to a format string
- print("we'd have {} beans,{} jars, and {} crates.".format(*formula))
习题25:定义函数
习题26:回顾以前知识
习题27:
- 这一节 就是讲解逻辑关系 逻辑术语的
- and or not != == >= <= True False
- 以及真值表详见P83
习题28:布尔表达式(跟C语言类似)
习题29:if语句
习题30: else 和 if 嵌套
- # else if
- people = 30
- cars = 40
- trucks = 15
- if cars > people:
- print("we should take the cars.")
- elif cars < people:
- print("We should not take the cars.")
- else:
- print("We can't decide.")
- if trucks > cars:
- print("That's too many trucks.")
- elif trucks < cars:
- print("Maybe we could take the trucks.")
- else:
- print("We still can't decide.")
- if people > trucks:
- print("Alright,let's just take the trucks.")
- else:
- print("Fine,let's stay home then.")
习题31:采用if-else语句编写问答式“小游戏”
练习使用嵌套判断语句
习题32:循环和列表
习题33:while循环
习题34:访问列表的元素
习题35:综合小练习,巩固前面所学知识
习题36:设计和调试
注:debug最佳方式就是 使用print在各个想要检查的关键点将变量打印出来,从而检查哪里是否有错!
习题37:复习各种符号
关键字 | 描述 | 示例 |
and | 逻辑与 | True and False == False |
as | with-as 语句的某一部分 | with X as Y: pass |
assert | 断言(确保)某东西为真 | assert False, "Error!" |
break | 立即停止循环 | while True: break |
class | 定义类 | class Person(object) |
continue | 停止当前循环的后续步骤,再做一次循环 | while True: continue |
def | 定义函数 | def X(): pass |
del | 从字典中删除 | del X[Y] |
elif | else if条件 | if: X; elif: Y; else: J |
else | else条件 | if: X; elif: Y; else: J |
except | 如果发生异常,运行此处代码 | except ValueError, e: print(e) |
exec | 将字符串作为Python脚本运行 | exec 'print("hello")' |
finally | 不管是否发生异常,都运行此处代码 | finally: pass |
for | 针对物件集合执行循环 | for X in Y: pass |
from | 从模块中导入特定部分 | from X import Y |
global | 声明全局变量 | global X |
if | if 条件 | if: X; elif: Y; /else: J |
import | 将模块导入当前文件以供使用 | import os |
in | for循环的一步分,也可以是否在Y中的条件判断 | for X in Y: pass 以及 1 in [1] == True |
is | 类似于==,判断是否一样 | 1 is 1 == True |
lambda | 船舰短匿名函数 | s = lambda y: y ** y; s(3) |
not | 逻辑非 | not True == False |
or | 逻辑或 | True or False == True |
pass | 表示空代码块 | def empty(): pass |
打印字符串 | print('this string') | |
raise | 出错后引发异常 | raise ValueError("No") |
return | 返回值并推出函数 | def X(): return Y |
try | 尝试执行代码,出错后转到except | try: pass |
while | while循环 | while X: pass |
with | 将表达式作为一个变量,然后执行代码块 | with X as Y: pass |
yield | 暂停函数返回到调用函数的代码中 | def X(): yield Y; X().next() |
数据类型 和 字符串转义序列 等详见P110--113
习题38:列表的操作
习题39:字典
小结:1)字典和列表有何不同?
答:列表是一些项的有序排列,而字典是将一些项(键)对应到另外一些项(值)的数据结构。
2)字典能用在哪里?
答:各章需要通过某个值取查看另一个值的场合。只要知道索引就能查到对应的值了。
3)有没有办法弄一个可以排序的字典?
答:看看python里的collections.OrderedDict数据结构。上网搜一下其文档和用法。
习题40: 模块、类和对象
question:为什么创建__init__或者别的类函数时需要多加一个self变量?
answer:如果不加self, cheese = 'Frank'这样的代码就有歧义了。它指的既可能使实例的cheese属性,也可能是一个叫cheese的局部变量。有了self.cheese = 'Frank'就清楚地知道这指的是实例的属性self.cheese.
习题41:学习面向对象术语
截取部分代码(在线读取文本信息)
- import random
- from urllib.request import urlopen
- import sys
- WORD_URL = "http://learncodethehardway.org/words.txt"
- WORDS = []
- # load up the words from the website
- for word in urlopen(WORD_URL).readlines():
- WORDS.append(str(word.strip(),encoding="utf-8"))
习题42:对象、类及从属关系
question1:对象和类的区别?
answer1: 对象和类好比 小狗和动物。对象是类的实例,也就是种特例。 书本例举的 鱼和泥鳅的关系。”is-a“和"has-a"的关系,”is-a“指的是鱼和泥鳅的关系,而”has-a“指的是泥鳅和鳃的关系。
注:一般定义类时,在类名后面没加(object),那么就默认添加(object)
习题43:编写命令行的小游戏!
习题44:继承和组合
- 隐式继承
- class Parent(object):
- def implicit(self):
- print("PARENT implicit()")
- class Child(Parent):
- pass
- dad = Parent()
- son = Child()
- dad.implicit()
- son.implicit()
- 输出如下所示:
PARENT implicit()
PARENT implicit() - 显示覆盖
- class Parent(object):
- def override(self):
- print("PARENT override()")
- class Child(Parent):
- def override(self):
- print("CHILD override()")
- dad = Parent()
- son = Child()
- dad.override()
- son.override()
- class Parent(object):
- def altered(self):
- print("PARENT altered()")
- class Child(Parent):
- def altered(self):
- print("CHILD, BEFORE PARENT altered()")
- super(Child, self).altered() # 采用super调用父类中的方法
- print("CHILD, AFTER PARENT altered()")
- dad = Parent()
- son = Child()
- dad.altered()
- print("-----------------------------")
- son.altered()
- python支持多继承 要用super()
- class SuperFun(Child, BadStuff):
- pass
- class SuperFun(Child, BadStuff):
笨方法学Python3(21-44)的更多相关文章
- 笨方法学python3
阅读<笨方法学python3>,归纳的知识点 相关代码详见github地址:https://github.com/BMDACMER/Learn-Python 习题1:安装环境+练习 pr ...
- "笨方法学python"
<笨方法学python>.感觉里面的方法还可以.新手可以看看... 本书可以:教会你编程新手三种最重要的技能:读和写.注重细节.发现不同.
- 笨方法学python 22,前期知识点总结
对笨方法学python,前22讲自己的模糊的单词.函数进行梳理总结如下: 单词.函数 含义 print() 打印内容到屏幕 IDLE 是一个纯Python下自带的简洁的集成开发环境 variable ...
- 《笨办法学Python3 》入坑必备,并不是真笨学!!!
<笨办法学Python3 >免费下载地址 内容简介 · · · · · · 本书是一本Python入门书籍,适合对计算机了解不多,没有学过编程,但对编程感兴趣的读者学习使用.这本书以习题的 ...
- [IT学习]Learn Python the Hard Way (Using Python 3)笨办法学Python3版本
黑客余弦先生在知道创宇的知道创宇研发技能表v3.1中提到了入门Python的一本好书<Learn Python the Hard Way(英文版链接)>.其中的代码全部是2.7版本. 如果 ...
- 笨方法学python--提示别人
1 上次学到使用raw_input(), 还可以如下使用: age = raw_input("age?") 2 命令名查看raw_input的说明 unit, pydoc raw_ ...
- 笨方法学python--安装和准备
1 下载并安装python http://python.org/download 下载python2.7. python2.7并不是python3.5的旧版本. python2现在应用较广,网上资料较 ...
- 《笨方法学Python》加分题32
注意一下 range 的用法.查一下 range 函数并理解它在第 22 行(我的答案),你可以直接将 elements 赋值为 range(0, 6) ,而无需使用 for 循环?在 python ...
- 《笨方法学Python》加分题20
加分练习通读脚本,在每一行之前加注解,以理解脚本里发生的事情.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量,在每次调用时,打印出 current_line ...
随机推荐
- N x N 的矩阵,顺时针旋转
第一种方法: 先打印外圈,再打印内圈 public class RotateMatrix1 { public static void rotate(int[][] matrix) { ; ; ; ]. ...
- SQL Server 10分钟理解游标
概述 游标是邪恶的! 在关系数据库中,我们对于查询的思考是面向集合的.而游标打破了这一规则,游标使得我们思考方式变为逐行进行.对于类C的开发人员来着,这样的思考方式会更加舒服. 正常面向集合的思维方式 ...
- 贪心 + 计算几何 --- Radar Installation
Radar Installation Description Assume the coasting is an infinite straight line. Land is in one side ...
- Docker-Compose搭建单体SkyWalking 6.2
SkyWalking简介 SkyWalking是一款高效的分布式链路追踪框架,对于处理分布式的调用链路的问题定位上有很大帮助 有以下特点: 性能好 针对单实例5000tps的应用,在全量采集的情况下, ...
- -Git Linux vi/vim 命令 按键 MD
目录 目录 Linux vi/vim 简介 vi/vim 的使用 命令模式 输入模式 底线命令模式 vi/vim 使用实例 使用 vi/vim 进入一般模式 按下 i 进入输入模式,开始编辑文字 按下 ...
- centOS 在线安装lnmp
CentOS7源码安装最新版LNMP环境 lnmp环境版本如下: 系统:CentOS 7 x86_64 NGINX:nginx-1.7.12 数据库:mariadb-10.0.13 PHP:php ...
- 让div在body中任意拖动
HTML代码 <div id="idOuterDiv" class="CsOuterDiv"> </div> CSS代码 body { ...
- dubbo循序渐进 - 使用Docker安装Nexus
docker search nexus docker pull docker.io/sonatype/nexus3 mkdir -p /usr/local/nexus3/nexus-data /usr ...
- UIPath RPA 自动化脚本 机器人从入门到精通
本文链接:https://blog.csdn.net/qq_27256783/article/details/93619818 一.UiPath介绍 UiPath 是RPA(Robotic Proce ...
- 【转载】 C#中手动创建一个DataTable对象并写入数据
在C#操作集合数据的过程中,有时候需要手动创建一个DataTable对象,并手动设置DataTable对象的Columns列名等信息,最后再往手动创建的DataTable对象中写入相应的数据信息,此时 ...