python2学习笔记
-
如何退出Python提示符
如果你使用的是Linux/BSDshell,那么按Ctrl-d退出提示符。如果是在Windows命令行中,则按Ctrl-z再按Enter
by the way,如果想在程序运行时中断执行或取消程序,按Ctrl-c -
行末的单独一个反斜杠\表示字符串在下一行继续,而不是开始一个新的行
"This is the first sentence.\ ... This is the second sentence." the same as 'This is the first sentence.This is the second sentence.' -
行连接:
明确的行连接如反斜杠。
还有一种暗示的假设,可以使你不需要使用反斜杠。这种情况出现在逻辑行中使用了圆括号、方括号或波形括号的时候。这被称为暗示的行连接。 -
关于左移、右移,按位操作
左移<<: 把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即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。 -
raw_input函数提供的是一个字符串,如果想要变为其他类型,则必须进行转换,如:转换为int:
guess = int(raw_input('Enter an integer : '))
-
注意布尔值的大小写问题:True、False(小写是错误的)
-
关于函数的可变参数、关键字参数如下:
可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例:def person(name, age, **kw): print 'name:', name, 'age:', age, 'other:', kw函数person除了必选参数name和age外,还接受关键字参数kw。在调用该函数时,可以只传入必选参数:
person('Michael', 30)
name: Michael age: 30 other: {}也可以传入任意个数的关键字参数:
person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other:关键字参数有什么用?它可以扩展函数的功能。比如,在person函数里,我们保证能接收到name和age这两个参数,但是,如果调用者愿意提供更多的参数,我们也能收到。试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。
要注意定义可变参数和关键字参数的语法:
*args是可变参数,args接收的是一个tuple;
**kw是关键字参数,kw接收的是一个dict。以上引自廖雪峰python教程,更多请见其网站
8.使用文档字符串DocStrings
#!/usr/bin/env python
#Filename:func_doc.py
def printMax(x,y):
'''Prints the maximun of two numbers.
The two values must be integers.'''
x=int(x)
y=int(y)
if x > y:
print x,'is maximum'
else:
print y,'is maximum'
printMax(3,5)
print printMax.__doc__
python func_doc.py
5 is maximum
Prints the maximum of two numbers.The two values must be integers.
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。强烈建议你在你的函数中使用文档字符串时遵循这个惯例。你可以使用__doc__(注意双下划线)调用printMax函数的文档字符串属性(属于函数的名称)。请记住Python把每一样东西 都作为对象,包括这个函数。
如果你已经在Python中使用过help(),那么你已经看到过DocStings的使用了!它所做的只是抓取函数的__doc__属性,然后整洁地展示给你。你可以对上面这个函数尝试一下——只是在你的程序中包括help(printMax)。记住按q退出help。
9.使用sys模块
sys模块包含了与Python解释器和它的环境有关的函数
#!/usr/bin/env python
#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 ['H:\Python', 'C:\Windows\system32\python27.zip', 'D:\Pyt
hon\DLLs', 'D:\Python\lib', 'D:\Python\lib\plat-win', 'D:\Python\lib\li
b-tk', 'D:\Python', 'D:\Python\lib\site-packages']
当Python执行import sys语句的时候,它在sys.path变量中所列目录中寻找sys.py模块。如果找到了这个文件,这个模块的主块中的语句将被运行,然后这个模块将能够被你 使用 。注意,初始化过程仅在我们第一次输入模块的时候进行。另外“sys”是“system”的缩写。
这里,当我们执行python using_sys.py we are arguments的时候,我们使用python命令运行using_sys.py模块,后面跟着的内容被作为参数传递给程序。Python为我们把它存储在sys.argv变量中。
记住,脚本的名称总是sys.argv列表的第一个参数。所以,在这里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。
10.使用模块的__name__
#!/usr/bin/python
# 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 itselfimport using_name
I am being imported from another module
每个Python模块都有它的__name__,如果它是'main',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。
11.dir()函数
你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。
>>>import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__s
tderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', ...]
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>> a=5
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'sys']
>>> del a
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
12.对象与引用
如果想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都引用同一个对象,那么如果不小心
的话,可能会引来各种麻烦。
mylist = shoplist # mylist is just another name pointing to the same object!
mylist = shoplist[:] # make a copy by doing a full slice
列表的赋值语句不创建拷贝,得使用切片操作符来建立序列的拷贝
13.str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。
>>> deli='_*_'
>>> mylist=['Brazil','Russia','India','China']
>>> print deli.join(mylist)
Brazil_*_Russia_*_India_*_China
>>> seq = ['1','2','3','4','5']
>>> sep = ','
>>> s = sep.join(seq)
>>> s
'1,2,3,4,5'
14.编写一个Python脚本--为我的所有重要文件创建备份的程序(压缩备份)
我们创建这个备份脚本的过程是编写程序的推荐方法——进行分析与设计
什么(分析) 如何(设计)
编写(实施) 测试(测试与调试)
使用(实施或开发) 维护(优化)
#!usr/bin/env python
#Filenname:backup_ver4.py
import os
import time
#1The files and directories to be backed up are specified in a list.
source=[r'H:\Python\backup']
#2The backup must be stored in a main backup directory
target_dir='H:\Python\save\\'
#3The files are backed up into a zip file.
#4The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment -->')
if len(comment)== 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
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) # make directory
print 'Successfully created directory', today
# The name of the zip file
# 5.we use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command="winrar a %s %s" %(target,' '.join(source))
# Run the backup
if os.system(zip_command)==0:
print 'Successful backup to',target
else:
print 'Backup Failed'
15.关于self:
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Person():
def sayHi(self):
print 'Hello,how are you?'
p=Person()
p.sayHi()
python method.py
Hello,how are you?
16.os模块中比较有用的部分如下:
● os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
● os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
● os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
● os.listdir()返回指定目录下的所有文件和目录名。
● os.remove()函数用来删除一个文件。
● os.system()函数用来运行shell命令。
● os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
● os.path.split()函数返回一个路径的目录名和文件名。
os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
● os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.exists()函数用来检验给出的路径是否真地存在。
17.exec和eval语句
exec语句用来执行储存在字符串或文件中的Python语句
exec 'print "Hello World"'
Hello World
eval语句用来计算存储在字符串中的有效Python表达式。
eval('2*3')
6

浙公网安备 33010602011771号