学习书籍:learn python the hard way
操作环境:Windows 7, PowerShell, Notepad++
开始时间:2016/11/23
阅读签到:11/23, 11/25, 11/28, 11/29, 11/30,12/9, 12/10,12/12, 12/13, 12/14, 12/15
阅读进度:exercise 29
1 打印字符串print
print "Hello World!" #此处双、单引号均可
2 注释符
NOTE:[csdn-markdown如何打出#字符-_-|||]
print "Hello World!" #comments
3 算术运算符与关系运算符
print "3 / 2 = ", 3 / 2
print "Is 3 greater than 2 ?", 3 > 2
输出:
3 / 2 = 1
Is 3 greater than 2 ? True
MORE: 注意此处逗号的连接作用
4 变量声明、赋值、打印
cars = 20
print cars, "cars available"
5 格式控制输出
province = "Zhejiang"
city = "Hangzhou"
print "Location: %s" % city
print "Let's talk about %s, %s." % (city, province)
6 字符串变量赋值、%r格式含义
x = "There are %d types of people." % 10
print "I said: %r." % x
7 输出相同、连续字符
#exr7
print "Its fleece was white as %s." % 'snow'
print "." * 10 #print 10 dots
print "Terry", #逗号的连接作用
print "Gump"
输出:
PS C:\Users\Administrator\Desktop> python.exe .\tst.py
Its fleece was white as snow.
..........
Terry Gump
8 %r格式控制符
分别作用于双引号字符串和单引号字符串(?):
#exr8
formatter = "%r %r %r %r"
print formatter % (formatter, formatter, formatter, formatter)
print "%r" % "I don't know why." #note the ' character
输出:
PS C:\Users\Administrator\Desktop> python.exe .\tst.py
'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
"I don't know why."
9 两种方法输出多行语句:转义字符\n与三个引号
#exr9
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: ", months
print """ #三个单引号亦可
There's something going on here.
With the three double- quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
10 三个单引号作用与三个双引号相同
-_-|||
11 raw_input 接收输入返回字符串
#exr11
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weight ?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." %(
age, height, weight)
MORE:
返回值转换为整型:int(raw_input())
raw_input() 将所有输入视为字符串输入;input()可接受合法的python表达式
12 raw_input使用提示符或者语句接受字符串
#exr12
age = raw_input("How old are you?")
print age
输出:
PS C:\Users\Administrator\Desktop> python.exe .\exr12.py
How old are you?22
22
MORE:
pydoc是python自带的模块,可用于浏览或者生成字符串文档(docstring)。
13 引入模块&接受参数(待修改)
#ex13
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
输出:
PS C:\Users\Administrator\Desktop> python.exe .\ex13.py a b c
The script is called: .\ex13.py
Your first variable is: a
Your second variable is: b
Your third variable is: c
14 使用提示符接收输入
#ex14
from sys import argv
script, user_name = argv
prompt = '> ' #NOTICE
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt) #NOTICE
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
输出:
PS C:\Users\Administrator\Desktop> python.exe .\ex14.py terry
Hi terry, I'm the .\ex14.py script.
I'd like to ask you a few questions.
Do you like me terry?
> yes
Where do you live terry?
> hangzhou
What kind of computer do you have?
> pc
Alright, so you said 'yes' about liking me.
You live in 'hangzhou'. Not sure where that is.
And you have a 'pc' computer. Nice.
15 打开和读取纯文本文件
#ex15
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read() #NOTICE "print" before "txt.read()"
txt.close() #NOTICE
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
输出:
PS C:\Users\Administrator\Desktop> python.exe .\ex15.py .\ex15.txt
Here's your file '.\\ex15.txt':
Time stands still,
Beauty in all she is.
I have been loving you for a thousand years, I'd love you for a thousand more.
Type the filename again:
> ex15.txt
Time stands still,
Beauty in all she is.
I have been loving you for a thousand years, I'd love you for a thousand more.
python命令行界面使用open
>>> filename = "ex15.txt"
>>> txt = open(filename)
>>> txt.read()
"Time stands still,\nBeauty in all she is.\nI have been loving you for a thousand years, I'd love you for a thousand more."
16 读写文件
常用函数列举
open
close
read
readline – 只读取文本文件的一行
truncate – 清空文件
write(stuff) – 写入stuff到文件
#ex16
from sys import argv
script, filename = argv
print "Going to erase %s." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit ENTER."
raw_input("?")
print "Opening %s..." % filename
target = open(filename, 'w')
print "Truncating %s..." % filename
target.truncate()
print "Enter 3 lines to write in:"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Write these to %s..." % filename
#target.write(line1)
#target.write("\n")
#target.write(line2)
#target.write("\n")
#target.write(line3)
#target.write("\n")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
#write同时接受多个字符串
print "Done!"
print "Reading to check it out..."
target = open(filename) #default in 'r' mode
print target.read()
raw_input("Hit ENTER to confirm.")
print("Closing the file...")
target.close() #疑问:此处open两次,close一次,会有什么隐藏的风险吗?
print "End."
输出:
PS C:\Users\Administrator\Desktop> python.exe .\ex16.py ex16.txt
Going to erase ex16.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit ENTER.
?
Opening ex16.txt...
Truncating ex16.txt...
Enter 3 lines to write in:
line 1: So cold, isn't it?
line 2: Yeah...Bad weather.
line 3: Get in please.
Write these to ex16.txt...
Done!
Reading to check it out...
So cold, isn't it?
Yeah...Bad weather.
Get in please.
Hit ENTER to confirm.
Closing the file...
End.
MORE:
open函数有三种打开方式’r’,’w’,’a’以及三种衍生的打开方式’r+’,’w+’,’a+’。
open函数默认打开方式是’r’。
在’w’模式下,写入之前通常进行擦除,防止生成乱码。
17 对多个文件操作:读写、拷贝等
from sys import argv
from os.path import exists #引用外部资源
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
#in_file = open(from_file)
#indata = in_file.read()
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit Enter to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
#in_file.close()
exists()函数用以判断文件是否存在。
len()函数返回文件占用长度。
18 使用关键字def定义函数
#单个参数
def fun1(arg):
print "arg: %r" % arg #函数定义语句均缩进4个字符
#多个参数
def fun2(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
#带星号参数代指多个参数
def fun3(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
#无参数
def fun4():
print "Nothing."
19 函数的参数传递
包括立即数、变量、表达式等均可。
20 自定义函数读取文件
成员函数seek()用于定位文件指针。
在print()函数后加上逗号,将取消打印print()自带行尾换行符。
21 函数返回值
使用return传递返回值
def add(a, b):
return a + b
23 互联网源码资源
bitbucket.org
github.com
gitorious.org
launchpad.net
sourceforge.net
freecode.com
24 使用return同时返回多个值
def fun(a):
b = a + 100
c = a * 100
d = a / 100
return b, c, d
e = int(raw_input())
f, g, h = fun(e)
25 字符串处理函数
类成员函数
split(char) 以char作为标志分隔句子得到单词集
pop(index) 返回以首单词(字符串)为基准,index为偏移量(可为负数)的单词(字符串)
def print_last_word(words):
last_word = words.pop(-1)
print last_word
系统函数
sorted(words) 给单词(字符串)排序
python解释器操作
以import加上源文件名(可省略’.py’)实现对其中资源的引用。\
输入变量回车,将直接打印变量值。\
help(srcfile)或者help(srcfile.fun),从源代码中获取帮助。
27 逻辑运算符
28 布尔运算练习
29 if语句
由于需要加快进度,终止阅读本书,另寻得《简明Python教程》一书,适宜速读。 12/15
学习书籍:简明Python教程
签到:12/15, 12/18++
12/15
使用自然字符串处理正则表达式,否则将需要使用很多的反斜杠。
print r"a regular experssion: \\\"
反斜杠还可起到连接不同物理行的逻辑行的作用。
print \
"hello world"
12/18
while循环可以附带一个else从句,尽管很少用到。
for循环根据序列决定循环次数而不是判断条件。也可以附带else从句。
for i in range(1, 5) #此处生成的序列为[1,2,3,4]
print i
else:
print 'The for loop is over'
函数
在函数内使用global语句可以引用函数外的变量。应尽量避免直接使用函数外的变量。
- 默认参数值
在形参名后加上赋值运算符(=)和默认值,可以给形参指定默认参数值。有默认值的形参必须放在形参表的末尾。 - 关键参数
使用名字(关键字)而不是位置来给函数指定实参。
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(25, c=24)
func(c=50, a=100)
pass语句表示一个空的语句块。
DocStrings文档字符串
文档字符串适用于函数、模块和类。
其惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。
对于函数,可以使用__doc__(双下划线)调用printMax函数的文档字符串属性(属于函数的名称)。help()所做的工作即抓取函数的__doc__属性。
模块
import语句可引入模块。
from .. import语句引入模块中的具体标识符。一般应避免使用。
from sys import * #输入sys模块中的所有标识符
sys.path第一个字符串是空的,代表当前目录。
模块的name属性 -> MORE
每个Python模块都有它的__name__,如果它是’__main__’,这说明这个模块被用户单独运行,可以进行相应的操作。
dir()返回模块定义的标识符列表。没有参数时返回当前模块中定义的标识符列表。
del语句删除当前模块中的变量/属性。
数据结构
通过[]索引具体项目:list[index]
列表,list类:方括号+用逗号分割项目,可变,序列
append方法:在列表尾添加项目
sort方法:给列表项排序
元组:圆括号+用逗号分割项目,不可变,序列
一个空的元组由一对空的圆括号组成。
含有单个元素的元组必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。
字典,dict类的对象:花括号,键(唯一):值,无序
键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。
items方法:返回一个由元组组成的列表,其中每个元组都包含一对项目——键与对应的值
in操作符/has_key方法:检验一个键/值对是否存在
序列
索引操作符
当索引是负数时,位置是从序列尾开始计算的。
切片操作符:序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号(必有)分割。
返回的序列从开始位置开始,在结束位置之前结束。