Chinaunix首页 | 论坛 | 博客
  • 博客访问: 298348
  • 博文数量: 53
  • 博客积分: 1266
  • 博客等级: 少尉
  • 技术积分: 572
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-16 16:45
文章分类

全部博文(53)

文章存档

2012年(37)

2011年(16)

分类: Python/Ruby

2012-10-16 21:46:38

【简明Python教程】
英文名:A Byte of Python
作者:Swaroop, C. H.

2、安装Python
(1)查看Python版本
python -V
(2)退出Python命令行shell
>>exit()

3、最初的步骤
(1)Hello World
print('hello world')
(2)使用源文件
python helloworld.py
(3)直接执行py文件
./helloworld.py
(4)获取帮助
>>help('print')

4、基本概念
(1)科学计数的浮点数
3.3E-2 或 3.3e-2
(2)复数
(-5.1 4.2j)
(3)引号
单引号和双引号作用相同;
三引号可以多行;
r"..."或r'...'中的内容可以不用转义;
u"..."或u'...'支持Unicode码;
'aa'"bvb"实现字符串连接
(4)标识符命名
字母或下划线开头;
其他部分由字母、数字和下划线组成;
(5)语句和程序行
用;分隔一行中的多个语句;
用\实现多行写一条语句;
(6)布尔值常量
True 和 False

5、运算符与表达式
幂 **
整除 //
与 或 非 and or not
位操作 &  |  ~   异或^

print('aaa','ddf')

6、控制流
【条件】
if 条件:
    执行
elif:
    执行
else:
    执行
【while循环】
while 条件:
    执行
else:
    执行
【for循环】
for i in range(0,100):
    执行
else:
    执行
【循环中使用到的】
break    跳出
continue 继续
pass     空行
【额外知识】
控制台输入:input('提示:')

7、函数
def 函数名(参数1,参数2):
    函数体
【返回值】
return
【局部变量】
函数体中通过赋值声明的变量
def f(x):
    x=2
【全局变量】
def f(x):
    global x
    x = 2
【默认参数值】
def f(x,a=1):
    执行
【关键参数】
def f(x,a=2,b=1):
    执行
f(3,7)
f(25,c=24)
f(c=50,a=100)
【DocStrings】
def f:
    '''Print.....

     The tow values
     ssssss'''

f.__doc__


8、模块
【何为模块】
模块就是一个py后缀的文件,模块名就是文件名
【使用模块】
import 模块名
from 模块名 import 变量名或函数名
使用from..import的好处是使用时可以省略模块名
【模块相关】
__name__ 模块名
__name__ == '__main__' 模块被用户单独运行
dir(模块名)  列出模块的所有函数、类和变量的名称
dir()        列出当前模块中的所有函数、类和变量的名称
del 名称     从上述列出的列表中删除某个模块或模块中的变量或函数
【字节文件】
.pyc
【sys模块】
import sys
sys.argv
sys.path

9、数据结构
【内建数据结构】
列表、元组、字典
【列表】
l=['a','c','b']
l.append('cc')
l.sort()
del l[1]
l[1:3]
l[1:]
l[1:-1]
l[:-1]
l[:]
【元组】
元组和列表的区别是元组是不能修改的。
z=('aa','dd','cc')
len(z)
【字典】
ab={'aa':'11','bb':'22','cc':'33'}
ab['bb']
del ab['cc']
if 'bb' in ab:
    print(ab['bb'])
【引用】
将对象赋给一个变量,该变量仅仅引用了那个对象
【字符串相关】
n="ssssdfdfdfdf"
n.startswith('ss')
n.endswith('f')
'd' in n
n.find('df')


ml=['Bv','Aa','dfd']
d.join(ml)
【带格式打印】
age=22
name='Ss'
print('%s is %d years old'%(name,age))

10、Python脚本示例
【需求】
1、需要备份的文件或目录列表;
2、指定主备份目录;
3、文件压缩成zip文件;
4、zip文件名为当前日期加时间;
5、完成压缩备份
【版本一】
import os
import time
# 1、需要备份的文件或目录列表;
source = ['/home/swaroop/byte', '/home/swaroop/bin']

source = [r'C:\Documents', r'D:\Work']

# 2、指定主备份目录;
target_dir = '/mnt/e/backup/'

# 3、文件压缩成zip文件;
# 4、zip文件名为当前日期加时间;
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'

# 5、完成压缩备份
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
    print('成功备份到',target)
else:
    print('备份失败')
【关键点】
import os
import time
time.strftime('%Y%m%d%H%M%S')
os.system(zip_command) == 0

【版本二】
需求:用当前日期做备份文件名,用当前时间做备份文件名
import os
import time
# 1、需要备份的文件或目录列表;
source = ['/home/swaroop/byte', '/home/swaroop/bin']

source = [r'C:\Documents', r'D:\Work']

# 2、指定主备份目录;
target_dir = '/mnt/e/backup/'

# 3、文件压缩成zip文件;
# 4、zip文件名为当前日期加时间;
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
if not os.path.exists(today):
    os.mkdir(today) # make directory
    print('Successfully created directory', today)
# The name of the zip file
target = today + os.sep + now + '.zip'

# 5、完成压缩备份
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
    print('成功备份到',target)
else:
    print('备份失败')
【关键点】
not os.path.exists(today)
os.mkdir(today)
os.sep

【版本三】
需求:把备份文件名和用户输入的注释关联
import os
import time
# 1、需要备份的文件或目录列表;
source = ['/home/swaroop/byte', '/home/swaroop/bin']

source = [r'C:\Documents', r'D:\Work']

# 2、指定主备份目录;
target_dir = '/mnt/e/backup/'

# 3、文件压缩成zip文件;
# 4、zip文件名为当前日期加时间;
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

# 用户输入注释
comment = 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)

# 5、完成压缩备份
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
    print('成功备份到',target)
else:
    print('备份失败')
【关键点】
comment.replace(' ', '_')

11、面向对象编程
【创建类】
class P:
    pass
a=P()
【使用对象方法】
class P:
    def s(self):
    print("HHHH")
p=P()
p.s()
【__init__方法】
class P:
    def __init__(self,name):
        self.name=name
    def s(self):
        print('H',self.name)
p=P('AAA')
p.s()
【使用类与对象的变量】
#!/usr/bin/python
# Filename: objvar.py
class Person:
    '''Represents a person.'''
    population = 0
    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name
        print('(Initializing %s)' % self.name)
        # When this person is created, he/she
        # adds to the population
        Person.population += 1
       
    def __del__(self):
        '''I am dying.'''
        print('%s says bye.' % self.name)
        Person.population -= 1
        if Person.population == 0:
            print('I am the last one.')
        else:
            print('There are still %d people left.' % Person.population)

    def sayHi(self):
        '''Greeting by the person.

        Really, that's all it does.'''
        print('Hi, my name is %s.' % self.name)

    def howMany(self):
        '''Prints the current population.'''
        if Person.population == 1:
            print('I am the only person here.')
        else:
            print('We have %d persons here.' % Person.population)

s=Person('Swarop')
s.sayHi()
s.howMany()
del s
【继承】
class 子类名(父类名):
    ......
【继承中使用父类的方法】
父类名.__init__(self, name, age)
父类名.父类方法名(self)

12、输入/输出
【文件】
f=open('路径加文件名','模式')#r读,w写,a追加
f.write(字符串);
while True:
    line = f.readline()
    if len(line)==0:
        break
    print(line)
f.close()
【存储器】
import pickle as p
fn='s.data'
l=['apple','mano','caro']
f=open(fn,'wb')
p.dump(l,f)
f.close()
f=open(fn,'rb')
l=p.load(f)
print(l)
f.close()

13、异常
【try..except】
try:
    a
except NameError:
    print('NameError')
except EOFError:
    print('EOFError')
except
    print('other except')
【引发异常】
#!/usr/bin/python
# Filename: a.py
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
        # Other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print('ShortInputException: The input was {0} long, expected at least {1}'.format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

python a.py
【try...finally】
try:
    ......
finally:
    ......

14、Python标准库
【sys模块】
sys.argv
sys.path
sys.exit()
sys.version
sys.version_info
【os模块】
os.name 操作系统名,nt是windows,posix是linux
os.getcwd() 当前工作目录
os.getenv('path')
os.putenv('名','值')
os.listdir('c:/')
os.remove('删除文件名')
os.linesep   回车换行符
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile('f:/')
os.path.isdir('f:/')
os.path.exists('f:/')

15、更多Python内容
【特殊的方法】
__init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self)      恰好在对象要被删除之前调用。
__str__(self)      在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other) 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
__getitem__(self,key) 使用x[key]索引操作符的时候调用。
__len__(self)         对序列对象使用内建的len()函数的时候调用。
【单语句块】
ifflag:print('Yes')
【列表综合】
>>> l1=[2,3,4]
>>> l2=[2*i for i in l1 if i > 2]
>>> l2
[6, 8]
【在函数中接收元组合列表】
>>> def po(p,*a):
...     print('p:',p)
...     print('*a:',a)
...
>>> po(2,3,4)
p: 2
*a: (3, 4)
>>> def bo(p,**a):
...     print('p:',p)
...     print('**a:',a)
...
>>> bo(2,a=3,b=4)
p: 2
**a: {'b': 4, 'a': 3}
【lambda】
>>> def make_repeater(n):
...     return lambda s: s*n
...
>>> twice = make_repeater(2)
>>> twice(8)
16
【执行字串或文件中的命令】
exec('print("Hello")')
【执行字符串中表达式】
eval('2*3')
【assert】
>>> m=['item']
>>> m.pop()
'item'
>>> assert len(m)>=1
Traceback (most recent call last):
  File "", line 1, in
AssertionError
【repr】
获取对象的可打印的表示形式。可以通过定义类的__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。
>>> i=[]
>>> i.append('item')
>>> repr(i)
"['item']"

16、接下来学什么?
【图形软件】
● PyQt 这是Qt工具包的Python绑定。Qt工具包是构建KDE的基石。Qt,特别是配合Qt
Designer和出色的Qt文档之后,它极其易用并且功能非常强大。
● PyGTK 这是GTK+工具包的Python绑定。GTK+工具包是构建GNOME的基石。
● wxPython 这是wxWidgets工具包的Python绑定。它的可移植性极佳,可以在Linux、
Windows、Mac甚至嵌入式平台上运行。有很多wxPython
的IDE,其中包括GUI设计器以及如SPE(Santi's Python Editor)和wxGlade那样的GUI开
发器。
● TkInter 这是现存最老的GUI工具包之一。如果你使用过IDLE,它就是一个TkInter程序。
在PythonWare.org上的TkInter文档是十分透彻的。TkInter具备可移植性,可以在Linux/
Unix和Windows下工作。重要的是,TkInter是标准Python发行版的一部分。
【更多内容】
● Jython是用Java语言实现的Python解释器。这意味着你可以用Python语言编写程序而同时
使用Java库!Jython是一个稳定成熟的软件。
● IronPython是用C#语言实现的Python解释器,可以运行在.NET、Mono和DotGNU平台
上。这意味着你可以用Python语言编写程序而使用.NET库以及其他由这三种平台提供的
库!
● Lython是Python语言的Lisp前段。它类似于普通的Lisp语言,会被直接编译为Python字节
码,这意味着它能与我们普通的Python代码协同工作。

阅读(3644) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~