$ python 13.py a b c
1.注意这里一共是4个命令行参数
2.命令行参数是作为str类型进入的,可以强制转换
###14.模拟一个命令行程序
###15.读取文件
.read()
###16.读写文件
close – Closes the file. Like File->Save.. in your editor.
read – Reads the contents of the file. You can assign the result to a variable.
readline – Reads just one line of a text file.
truncate – Empties the file. Watch out if you care about the file.
write(stuff) – Writes stuff to the file.
What does the * in *args do?
That tells Python to take all the arguments to the function and then put them in args as a list. It’s like argv that you’ve been using, but for functions. It’s not normally used too often unless specifically needed.
That’s a list in a list like this: [[1,2,3],[4,5,6]]
###33.while循环
###34.获取列表元素
###35.分支和函数
1. exit(0)
from sys import exit
2. in关键字
###36.设计和debug
Rules For If-Statements
Every if-statement must have an else.
If this else should never be run because it doesn’t make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Never nest if-statements more than two deep and always try to do them one deep. This means if you put an if in an if then you should be looking to move that second if into another function.
Treat if-statements like paragraphs, where each if elif else grouping is like a set of sentences. Put blank lines before and after.
Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.
Rules For Loops
Use a while-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different.
while仅仅用于无限循环
Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
其他情况用for
Tips For Debugging
Do not use a “debugger.” A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn’t help and is just confusing.
The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.
Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.
###37.符号复习
Keywords
关键字
功能
and
逻辑与
del
解除变量和特性的绑定
from
指明导入模块来源
not
否
while
循环
as
elif
else if
global
标记一个变量为全局变量
or
或
with
使用上下文管理器对代码块进行包装
assert
断言
else
if
pass
空语句
yield
暂时中止生成器的执行并且生成一个值
break
跳出
except
import
导入
print
打印
class
类
exec
执行包含Python语句的字符串
in
成员资格测试
raise
引发异常
continue
继续
finally
is
一致性测试
return
返回
def
定义函数
for
for循环
lambda
lambda表达式
try
封闭一段可能发生异常的代码
Data Types :有二十几种
True
False
None
strings
numbers:
floats
lists
String Formats
%d
%i
%o
%u
%x
%X
%e
%E
%f
%F
%g
%G
%c
%r
%s
%%
Operators
** :乘方
{ }
@
,
:
.
;
Reading Code
如何阅读代码
Functions and what they do.
Where each variable is first given a value.
Any variables with the same names in different parts of the program. These may be trouble later.
Any if-statements without else clauses. Are they right?
Any while-loops that might not end.
Finally, any parts of code that you can’t understand for whatever reason.
###38.操作列表
复制列表
When To Use Lists
If you need to maintain order.
If you need to access the contents randomly by a number.
If you need to go through the contents linearly (first to last).
###39.字典,可爱的字典
获取字典值
添加字典元素
删除字典元素
两种获取可能不存在元素的方法
Making Your Own Dictionary Module创建自己的字典模组
没完成
###40.模组,类和对象
1.模块就像字典
2.类就像模块
3.对象就像迷你import
一个简单的类
###41.面向对象
一些名词
class : Tell Python to make a new kind of thing.
object : Two meanings: the most basic kind of thing, and any instance of some thing.
instance : What you get when you tell Python to create a class.
def : How you define a function inside a class.
self : Inside the functions in a class, self is a variable for the instance/object being accessed.
inheritance : The concept that one class can inherit traits from another class, much like you and your parents.
composition : The concept that a class can be composed of other classes as parts, much like how a car has wheels.
attribute : A property classes have that are from composition and are usually variables.
is-a : A phrase to say that something inherits from another, as in a “salmon” is-a “fish.”
has-a : A phrase to say that something is composed of other things or has a trait, as in “a salmon has-a mouth.”
###42.对象和类
###43.基本面向对象分析与设计思想
Write or draw about the problem.
Extract key concepts from #1 and research them.
Create a class hierarchy and object map for the concepts.
Code the classes and a test to run them.
Repeat and refine..
###44.继承和聚合
####继承
1.成员函数继承
you define a function in the parent, but not in the child.
~
2.成员函数重载
3.事先/事后改变重载
4.super()的意义
5.在__init__中使用super()
这是最常见的用法
####聚合
####何时使用聚合,何时使用继承
You don’t want to have duplicated code all over your software, since that’s not clean and efficient
Inheritance solves this problem by creating a mechanism for you to have implied features in base classes.
Composition solves this by giving you modules and the ability to simply call functions in other classes.
###45.编写一个游戏
###46.项目框架
1.安装python包
I am warning you; this will be frustrating. In the business we call this “yak shaving.” Yak shaving is any activity that is mind numblingly, irritatingly boring and tedious that you have to do before you can do something else that’s more fun. You want to create cool Python projects, but you can’t do that until you set up a skeleton directory, but you can’t set up a skeleton directory until you install some packages, but you can’t install packages until you install package installers, and you can’t install package installers until you figure out how your system installs software in general, and so on.
2.建立框架
3.使用框架
Using the Skeleton
Make a copy of your skeleton directory. Name it after your new project.
Rename (move) the NAME module to be the name of your project or whatever you want to call your root module.
Edit your setup.py to have all the information for your project.
Rename tests/NAME_tests.py to also have your module name.
Double check it’s all working by using nosetests again.
Start coding
Copy skeleton to “your_project”.
Rename everything with NAME to your_project.
Change the word NAME in all the files to your_project.
Finally, remove all the *.pyc files to make sure you’re clean.
Test files go in tests/ and are named BLAH_tests.py otherwise nosetests won’t run them. This also keeps your tests from clashing with your other code.
Write one test file for each module you make.
Keep your test cases (functions) short, but do not worry if they are a bit messy. Test cases are usually kind of messy.
Even though test cases are messy, try to keep them clean and remove any repetitive code you can. Create helper functions that get rid of duplicate code. You will thank me later when you make a change and then have to change your tests. Duplicated code will make changing your tests more difficult.
Finally, do not get too attached to your tests. Sometimes, the best way to redesign something is to just delete it and start over.
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
###48.高级用户输入
1. 分割句子
2.元组
类似于一个你不能修改的列表
元组由不同的元素组成,每个元素可以存储不同类型的数据,例如,字符串、数字和元组
元组通常代表一行数据,而元组中的元素则代表不同的数据项
创建元组,不定长,但一旦创建后则不能修改长度
元组是由,创建的,只是放在()里面而已,如果只有一个元素,逗号也不能省
3.异常
Except 和 raise
An exception is an error that you get from some function you may have run.
try-except和if-else的选择
if-else是用一个返回值进行判断,try-except则是根据异常来进行判断
4.如果保证自己写的模组能够正确导入Why do I keep getting ImportErrors?
Import errors are caused by usually four things.
You didn’t make a init.py in a directory that has modules in it.
you are in the wrong directory.
You are importing the wrong module because you spelled it wrong.
Your PYTHONPATH isn’t set to . so you can’t load modules from your current directory.
###49.造句
查表和配对
A way to loop through the list of tuples. That’s easy.
A way to “match” different types of tuples that we expect in our Subject Verb Object setup.
A way to “peek” at a potential tuple so we can make some decisions.
A way to “skip” things we do not care about, like stop words.
The Sentence Grammar
With our tools we can now begin to build Sentence objects from our list of tuples. What we do is a process of:
Identify the next word with peek.
If that word fits in our grammar, we call a function to handle that part of the grammar, say parse_subject.
If it doesn’t, we raise an error, which you will learn about in this lesson.
When we’re all done, we should have a Sentence object to work with in our game.