简
明Python 教
程
第四章.基本概念
1.单引号与双引号意义相同,三引号可以输出回车。当要输出的字符串里包含单引号和双
引号还有换行时,可以使用三引号。如:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
2.如果要输出what’s your name可以使用\’来表示’,以免python无法识别如何闭合’,\\
可以表示\本身。当\放在字符串句尾时,可以回车继续写下一行。如:
print 'what\'s your name'
what's your name
和
"This is the first sentence.\
This is the second sentence."
1.字母或下划线开头,对大小写敏感。
第五章.运算符与表达式
+,加。
-,减。
*,乘。
**,幂,2**3得到8,即2的三次幂。
/,除,4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333。//,取整除,4//3.0得到1.0。
%,取模,返回除法的余数,如9%2得1。
<<,左移,把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1),2 << 2得到8。——2按比特表示为10。
>>,右移,把一个数的比特向右移一定数目,11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。
&,按位与数的按位与,5 & 3得到1。
|,按位或数的按位或,5 | 3得到7。
^,按位异或数的按位异或,5 ^ 3得到6
~,按位翻转x的按位翻转是-(x+1),~5得到-6。
<,小于,所有比较运算符返回1表示真,返回0表示假,5<3返回0(即False)而3<5返回1(即True)。比较可被任意连接:3<5<7返回True。
>,大于。
<=,小于等于。
>=,大于等于。
==,等于,比较对象是否相等,x = 2;y = 2;x == y返回True。X = ’str’;y = ‘stR’;x == y返回False。x = 'str'; y = 'str'; x == y返回True。
!=,不等于,x = 2; y = 3; x != y返回True。
Not,布尔“非”,如果x为True,返回False。如果x为False返回True。x = True;not x返回False。
And,布尔“与”,一个为假就为假。
Or,布尔“或”,一个为真就为真。
最好用()来区分运算优先
第六章.控制流
#Filename:if.py
number = 23
guess = int(raw_input('Enter an integer:'))
if guess == number:
print 'u r right'
elif guess < number:
print 'u r wrong,it is a little higher than it'
else:
print 'u r wrong,it is a little lower than that'
print 'Done'
#Filename:while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer:'))
if guess == number:
print 'u r right'
running = False
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
print 'Done'
range(1,5)给出序列[1,2,3,4]默认步进1,如果range(1,5,2)则序列为[1,3]步进为2。
#FIlename:for.py
for i in range(1,5):
print i
else:
print 'The for loop is over'
for循环在这个范围内递归,for I in range(1,5)等价于for I in [1,2,3,4],如同把序列中的每个数赋值给i,一次一个,然后以每个i的值执行这个模块。
Else的值是可选的,它总是在for循环结束后执行一次,除非遇到break。
# Filename: break.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
#Filename:continue.py
while True:
s = raw_input('Enter sth:')
if s == 'quit':
print 'u r righr!'
break
if len(s) < 3:
continue
print 'Inpur is of sufficient length'
第七章.函数#Filename:function1.py
def sayHello():
print 'Hello python!'
sayHello()
#Filename:fuc_param.py
def printMax(a , b):
if a > b:
print a, 'is maximum'
else:
print b, 'is maximum'
printMax(3 , 4)
x = 5
y = 7
printMax(x , y)
1.
# Filename: func_local.py
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x
结果:
x is 50
Changed local x to 2
x is still 50
2.global语句
# Filename: func_global.py
def func():
global x
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
结果:
x is 50
Changed local x to 2
Value of x is 2
#Filename:func_default.py
def say(message , times = 1):
print message*times
say('hello')
say('World' , 5)
结果:
hello
WorldWorldWorldWorldWorld
重要
只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。
这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是无效的。
#Filename:func_key.py
def func(a , b = 5 , c = 10):
print 'a is ', a ,'and b is' , b ,'and c is ' , c
func(3 , 7)
func(25 , c = 24)
func(c = 50 , a = 100)
结果:
a is 3 and
b is 7 and
c is 10
a is 25 and
b is 5 and
c is 24
a is 100 and
b is 5 and
c is 50
#Filename:func_return.py
def maximum(x , y):
if x > y:
return x
else:
return y
print maximum(3 , 4)
结果:4
注意,没有返回值的return语句等价于return None。None是Python中表示没有任何东西的特殊类型。例如,如果一个变量的值为None,可以表示它没有值。
#Filename:func_doc.py
def printmax(x , y):
'''First
third.'''
x = int (x)
y = int (y)
if x > y:
print x,'is max'
else:
print y,'is max'
printmax(5,6)
print printmax.__doc__
结果:
6 is max
First
third.
第八章.模块
# Filename: using_sys.py
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
执行:python using_sys.py we are arguments
结果:
The command line arguments are:
using_sys.py
we
are
arguments
The PYTHONPATH is ['E:\\hack\\stu\\python\\stu_test', 'D:\\Python26\\Lib', 'C:\\
WINDOWS\\system32\\python26.zip', 'D:\\Python26\\DLLs', 'D:\\Python26\\lib\\plat
-win', 'D:\\Python26\\lib\\lib-tk', 'D:\\Python26', 'D:\\Python26\\lib\\site-pac
kages', 'D:\\Python26\\lib\\site-packages\\win32', 'D:\\Python26\\lib\\site-pack
ages\\win32\\lib', 'D:\\Python26\\lib\\site-packages\\Pythonwin', 'D:\\Python26\
\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info']
执行过程:import sys是告诉系统使用sys模块。python using_sys.py we are arguments是用python命令运行using_sys.py模块,后面跟着的we are arguments被作为参数传递给程序,python为我们把它存储在sys.argv变量中。for i in sys.argv:是将sys.argv中的变量内容赋给i,然后输出i,这里需要注意。脚本名称即using_sys.py总是sys_argv的第一个参数,即sys.argv[0],'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。
输入一个模块相对来说是一个比较费时的事情,所以Python做了一些技巧,以便使输入模块更加快一些。一种方法是创建字节编译的文件,这些文件以.pyc作为扩展名。字节编译的文与Python变换程序的中间状态有关。当你在下次从别的程序输入这个模块的时候,.pyc 文件是十分有用的——它会快得多,因为一部分输入模块所需的处理已经完成了。另外,这些字节编译的文件也是与平台无关的。所以,现在你知道了那些.pyc文件事实上是什么了。
如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
运行:python using_name.py
结果:This program is being run by itself
运行:python
Import using_name
结果:I am being imported from another module
1.
#Filename:mymodule.py
def sayhi():
print 'hi'
version = '0.1'
========================================
#Filename:mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version',mymodule.version
运行:python mymodule_demo.py
结果:
hi
Version 0.1
2.用from..import写
# Filename: mymodule_demo2.py
from mymodule import sayhi, version
sayhi()
print 'Version', version
是一样的。
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__s tderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_g etframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_trac
ing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode
', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable
', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'get filesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeo
f', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunic
ode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'plat form', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile',
'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'ver
sion', 'version_info', 'warnoptions', 'winver']
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>> a = 5
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'sys']
>>> del a
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>
第九章.数据结构
列表是可变的数据类型。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。
利用:
#Filename:using_list.py
shoplist = ['apple','banana','mango','carrot']
print 'i have' ,len(shoplist),'items to purchase.'
print 'they r:',
for items in shoplist:
print items,
print '\n i also have to buy rice'
shoplist.append('rice')
print 'now,my shoplist is:',shoplist
print 'i will sort my list'
shoplist.sort()
print 'Sorted shopping list is:',shoplist
print 'The first item i will but is:',shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'i bought the',olditem
print 'my shopping list is now:',shoplist
结果:
i have 4 items to purchase.
they r: apple banana mango carrot
i also have to buy rice
now,my shoplist is: ['apple', 'banana', 'mango', 'carrot', 'rice']
i will sort my list
Sorted shopping list is: ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item i will but is: apple
i bought the apple
my shopping list is now: ['banana', 'carrot', 'mango', 'rice']
元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
1.
#Filename:using_tuple.py
zoo = ('wolf','elephant','penguin')
print 'Number of animals in zoo is', len(zoo)
new_zoo = ('monkey','dolphin',zoo)
print 'Number of animals in the new zoo is',len(new_zoo)
print 'All animals in new zoo are',new_zoo
print 'Animals brought from old zoo are',new_zoo[2]
print 'Last animails brought from old zoo is',new_zoo[2][2]
结果:
Number of animals in zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animails brought from old zoo is penguin
2.使用元组输出
#Filename:print_tuple.py
age = 22
name = 'bande'
print '%s is %d years old' %(name , age)
print 'why is %s playing with that python?' % (name)
结果:
bande is 22 years old
why is bande playing with that python?
键必须是唯一的,你只能使用不可变的对象比如字符串来作为字典的键,但是可变或不可变的对象可以作为值。#Filename:using_dict.py
ab = {'Swaroop' : 'swaroopch@https://www.doczj.com/doc/0a3070645.html,',
'Larry' : 'larry@https://www.doczj.com/doc/0a3070645.html,',
'Matsumoto' : 'matz@https://www.doczj.com/doc/0a3070645.html,',
'Spammer':'spammer@https://www.doczj.com/doc/0a3070645.html,'
}
print 'Swaroop\'s address is %s' %ab['Swaroop']
ab['Guido'] = 'guido@https://www.doczj.com/doc/0a3070645.html,'
del ab['Spammer']
print '\nTher are %d contacts in the address-book\n' % len(ab) for name,address in ab.items():
print 'Contact %s at %s' % (name,address)
if 'Guido' in ab:
print '\nGuido\'s address is %s' % ab['Guido']
结果:
Swaroop's address is swaroopch@https://www.doczj.com/doc/0a3070645.html,
Ther are 4 contacts in the address-book
Contact Swaroop at swaroopch@https://www.doczj.com/doc/0a3070645.html,
Contact Matsumoto at matz@https://www.doczj.com/doc/0a3070645.html,
Contact Larry at larry@https://www.doczj.com/doc/0a3070645.html,
Contact Guido at guido@https://www.doczj.com/doc/0a3070645.html,
Guido's address is guido@https://www.doczj.com/doc/0a3070645.html,
#Filename:seq.py
shoplist = ['apple','mango','carrot','banana']
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is',shoplist[1:-1]
print 'Item start to end is',shoplist[:]
name = 'evilcoda'
print 'characters 1 to 3 is',name [1:3]
print 'characters 2 to end is',name [2:]
print 'characters 1 to -1 is', name [1:-1]
print 'characters start to end is',name[:]
结果:
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is vi
characters 2 to end is ilcoda
characters 1 to -1 is vilcod
characters start to end is evilcoda
#Filename:reference.py
print 'Simple Assignment'
shoplist = ['apple','mango','carrot','banana']
mylist = shoplist
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
mylist = shoplist[:]
del mylist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
结果:
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
当创建一个对象并给他赋变量的时候,这个变量仅仅是引用那个对象,不是表示这个对象本身,也就是说,变量名指向计算机中存储那个对象的内存。
上面的程序提醒我们,需要注意的是,如果想要复制一个列表或者类似的序列或者其他复杂的对象的时候,必须用切片操作符来操作才行,比如上面程序的mylist = shoplist之后,del shoplist[0],然后输出shoplist 和mylist发现mylist里面的mylist[0]也没了,但是如果像下面的那句mylist = shoplist[:],然后del mylist[0],现在尝试输出shoplist和mylist,发现只有mylist[0]被删了,shoplist[0]还在。
#Filename:str_methods.py
name = 'Evilcoda'
if name.startswith('Evi'):
print 'yes , the string starts with "Evi"'
if 'a' in name:
print 'Yes , it contains the string "a"'
if name.find('coda') != -1:
print 'Yes , it contains the string "coda"'
ddd = '|'
mylist = ['Brazil' , 'Russia' , 'India' , 'China']
print ddd.join(mylist)
结果:
yes , the string starts with "Evi"
Yes , it contains the string "a"
Yes , it contains the string "coda"
Brazil|Russia|India|China
第十章.解决问题——编写一个python脚本
编写一个软件的环节:
1. 什么(分析)
2. 如何(设计)
3. 编写(实施)
4. 测试(测试与调试)
5. 使用(实施或开发)
6. 维护(优化)
实例:创建一个可以为我的所有重要文件创建备份的程序。
需要考虑:
1. 需要备份的文件和目录由一个列表指定。
2. 备份应该保存在主备份目录中。
3. 文件备份成一个zip文件。
4. zip存档的名称是当前的日期和时间。
5. 使用zip命令执行命令来进行备份。
'''版本一'''
#!/usr/bin/python
# Filename: backup_ver1.py
import os#使用os模块
import time#使用time模块
source = ['/home/swaroop/byte', '/home/swaroop/bin']#需要进行备份的文件或者目录
target_dir = '/mnt/e/backup/' # 备份的目标目录
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'#文件名,用+连接字符串
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))#zip的备份命令
if os.system(zip_command) == 0:#使用os.system函数运行命令,如果运行成功返回0否则返回错误号
else:
print 'Backup FAILED'
'''版本二'''
#!/usr/bin/python
# Filename: backup_ver2.py
import os
import time
source = ['/home/swaroop/byte', '/home/swaroop/bin']
target_dir = '/mnt/e/backup/'
today = target_dir + time.strftime('%Y%m%d')#目标主目录中以今天年月日命名的目录now = time.strftime('%H%M%S')#现在的时分秒
if not os.path.exists(today):#如果目标主目录中没有以今天年月日命名的目录
os.mkdir(today) # 创建目标主目录中以今天年月日命名的目录
print 'Successfully created directory', today
target = today + os.sep + now + '.zip'#备份的文件名
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
'''版本三'''
#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
source = ['/home/swaroop/byte', '/home/swaroop/bin']
target_dir = '/mnt/e/backup/'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('Enter a comment --> ')
if len(comment) == 0:
target = today + os.sep + now + '.zip'#os.sep可以取代操作系统特定的路径分割符else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today)
print 'Successfully created directory', today
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
else:
print 'Backup FAILED'
'''版本四'''
#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
source = ['/home/swaroop/byte', '/home/swaroop/bin']
target_dir = '/mnt/e/backup/'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('Enter a comment --> ')
if len(comment) == 0:
target = today + os.sep + now + '.zip'#os.sep可以取代操作系统特定的路径分割符
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'#把描述里的空格换成下划线
if not os.path.exists(today):
os.mkdir(today)
print 'Successfully created directory', today
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
注意:版本三出错,版本四对版本三的修正只更改了一个地方,就是target = today + os.sep + now + '_' +这后面加了个\变成target = today + os.sep + now + '_' + \,因为在+后面没有任何操作数,而我们也没有指明下面的那一行物理行与这一行是同一个逻辑行,所以+不知道如何操作,我们想到之前的输出字符串的时候可以在一句话的句尾加上\然后回车继续写下一句,这里也一样,我们在后面加上\来表示逻辑行在下一物理行继续,修订成功。
重要
我们创建这个备份脚本的过程是编写程序的推荐方法——进行分析与设计。开始时实施一个简单的版本。对它进行测试与调试。使用它以确信它如预期那样地工作。再增加任何你想要的特性,根据需要一次次重复这个编写-测试-使用的周期。记住“软件是长出来的,而不是建造的”。
第十一章.面向对象的编程
对象与实例的区别
对象只是定义实例应该怎样产生,而实例是在内存中实实在在存在的数据。实例只有当程序启动时才存在。对象则不需要程序启动。
你一定很奇怪Python如何给self赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1,arg2)——这就是self的原理了。
#Filename:simplestclass.py
class Person:
pass
p = Person()
print p
结果: