Python简介
Upcoming SlideShare
Loading in...5
×
 

Python简介

on

  • 2,286 views

 

Statistics

Views

Total Views
2,286
Views on SlideShare
1,996
Embed Views
290

Actions

Likes
0
Downloads
18
Comments
0

2 Embeds 290

http://bluehua.org 289
url_unknown 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Python简介 Python简介 Presentation Transcript

  • Python 简介
    emptyhua@gmail.com
  • 起源
    Python的创始人为Guido van Rossum。1989年圣诞节期间,Guido为了打发圣诞节的无趣,决心开发一个新的脚本解释程序,做为 ABC 语言的一种继承。之所以选中 Python(大蟒蛇的意思)作为程序的名字,是因为他是一个Monty Python的飞行马戏团的爱好者。
    主要版本:2.4,2.6,2.7,3.0
  • 优点
    简单
    通用,类库丰富
    容易扩展
  • 简单
    应该把大部分心思放到业务本身,而非正在使用的编程语言
    写了一年还没湿的JS?十分钟就会忘掉NB语法的perl?特性神秘莫测的php?恼人mem leak的C?不用IDE都不知怎么写代码的java?
    Python哥已经超脱了
  • 通用
    平台unix,window,symbian
    领域:系统管理,图形编程,web和网络编程
    各领域均有成熟优秀的类库:Zope,Django,twisted,pygtk,pyqt
  • 易于扩展
    C和python写的模块可以完美结合,性能和灵活兼备
    通过ctype还可以直接调用c的动态链接库
    >>> cdll.LoadLibrary("libc.so.6”)
    <CDLL 'libc.so.6', handle ... at ...>
    >>> libc = CDLL("libc.so.6”)
    >>> print libc.time(None)
    1150640792
  • 缺点
    强制换行,用惯了{}会不习惯,但是python程序员会说这正是python的优点,让你不能编写层次太深的嵌套,否则会找不到下一段代码去哪开头
  • Hello python
    统计单词数
    #!/usr/bin/env python
    import sys
    words = 0
    for line in file(sys.argv[1]):
    words += line.strip().count(' ') + 1
    print 'words:%d' % words
  • 基本类型
    整形,浮点(int, float)
    布尔(bool:True False)
    序列:
    字符串(str)
    列表(list)
    元组(tuple)
    字典(dict)
    集合(set)
  • 字符串
    >>> a = 'i am a string’
    >>> a[0]
    'i'
    >>> a[:-6]
    'i am a ’
    >>> 'a' * 5
    'aaaaa’
    >>> a[:-6] + 'long string'
    'i am a long string’
    >>> print 'new line n second line'
    new line
    second line
    >>> print r'new line n second line'
    new line n second line
    >>> 'a' in 'abc’
    True
    >>> 'd' in 'abc'
    False
    #字符串,List,Tuple均支持[] [:] + * in操作符 len()取长度
  • 列表List
    #list,tuple,dict可存取任何类型的数据
    >>> a = [1,2,3,4]
    >>> a
    [1, 2, 3, 4]
    >>> b = range(5,8)
    >>> b
    [5, 6, 7]
    >>> c = a + b
    >>> c
    [1, 2, 3, 4, 5, 6, 7]
    >>> c.append(8)
    >>> c
    [1, 2, 3, 4, 5, 6, 7, 8]
    >>> c.remove(2)
    >>> c
    [1, 3, 4, 5, 6, 7, 8]
  • 列表List
    #!/usr/bin/env python
    a = ['a','b','c','d']
    for v in a:
    print v
    for i, v in enumerate(a):
    print i, v
    b = [i + '-' for i in a]
    b = [i + '-' for i in a if i != 'c']
  • 元组Tuple
    >>> a = (1,)
    >>> a
    (1,)
    >>> b = (2,3)
    >>> b
    (2, 3)
    >>> c = a + b
    >>> c
    (1, 2, 3)
    >>> c.remove(2)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'tuple' object has no attribute 'remove'
  • 字典Dict
    #字典的key可是是任何可以hash的对象
    >>> a = {'name':'han meimei'}
    >>> a['age'] = 14
    >>> a
    {'age': 14, 'name': 'han meimei'}
    >>> del a['age']
    >>> a
    {'name': 'han meimei'}
    >>> b = (1,2,3)
    >>> a[b] = 'hello'
  • If
    #python里木有switch
    if a < 250 or a > 250:
    print 'good man'
    elif False:
    print 'i am lonely'
    else:
    print 'bad man'
  • Loop
    #python里木有for (;;)
    for x in xrange(50, 100):
    print x
    for v in [1,2,3,4,5,6]:
    print v
    while x < 10:
    print x
    x += 1
  • 异常处理
    #!/usr/bin/env python
    import traceback
    try:
    print a
    except NameError, e:
    print traceback.format_exc()
    raise NameError, 'hoho'
    except Exception, e:
    print 'catch all’
    Traceback (most recent call last):
    File "tmp.py", line 6, in <module>
    print a
    NameError: name 'a' is not defined
    Traceback (most recent call last):
    File "tmp.py", line 9, in <module>
    raise NameError, 'hoho'
    NameError: hoho
  • 定义函数
    def foo(x,y):
    return x * y
    print foo(3, 5)
    变参
    def foo(*m):
    return ','.join(m)
    print foo('1','2','3','4')
    def foo(**m):
    return ','.join(m.keys())
    print foo(name='oo',age='xx')
    匿名函数
    (lambda i: 'good %s' % i)('man')
  • 函数修饰符
    #!/usr/bin/env python
    def add_copyright(fn):
    def rtfn(*args):
    return fn(*[i + '@by youlu' for i in args])
    return rtfn
    @add_copyright
    def render_str(title, body):
    print title
    print body
    render_str('hello', 'i am the body')
    hello@by youlu
    i am the body@by youlu
  • 使用文档
    对于字符串型的注释 如果注释出现在文件开头,那么它将成为一个模块文档
    如果出现在函数定义之后,成为一个函数文档
    如果出现在class定义之后,成为一个类的说明文档
    文档在运行时是可以访问的
    >>> def foo():
    ... '''
    ... i am foo
    ... void foo(void);
    ... '''
    ... pass
    ...
    >>>print foo.__doc__
    i am foo
    void foo(void);
    >>>help(foo)
    >>>import os
    >>>help(os)
  • 使用正则
    #!/usr/bin/env python
    import re
    TAGREG = re.compile(r'<[^>]*>')
    test = '''
    <html>i am a html doc</html>
    '''
    print re.sub(TAGREG, '', test)
    print TAGREG.sub('', test)
    print re.findall(TAGREG, test)
    print TAGREG.findall(test)
  • 系统编程常用
    #!/usr/bin/env python
    import sys
    #获取标准输入
    for line in sys.stdin:
    print line
    #标准输出
    print "message”
    #标准错误输出
    print>> sys.stderr,”Error”
    #处理参数
    print ','.join(sys.argv)
    #修改标准输出
    sys.stdout = open('./screenlog’,’a’)
  • 系统编程常用
    #!/usr/bin/env python
    import urllib
    import os
    #请求url
    wget = urllib.urlopen
    content = wget('http://g.cn').read()
    print content
    #调用外部程序
    os.system('ls')
    print os.popen('ls').read()