SlideShare a Scribd company logo
Python Story 陈小玉  <smallfish.xy@gmail.com> twitter: @nnfish blog:  http://chenxiaoyu.org
历史由来 阿姆斯特丹 1989 年圣诞节期间 Guido van Rossum  为了打发圣诞节的无趣 决心开发一种新的解释性程序 … 不久之后,一个叫 Python 的语言就诞生了! 注: Guido 又称龟叔或者莽爹  :_)
能做什么 系统编程 GUI  应用 网络应用 数据库应用 WEB 应用 快速开发模型 游戏、人工智能、图像等 …  more
谁在用 Google YouTube Bittorrent Facebook Digg Dropbox Opera Reddit Sourceforge 豆瓣 搜狐邮箱 金山 …  more
优势 免费、开源 跨平台 简单易学 快速开发 类库丰富 易扩展 可嵌入性
版本信息 2.x 2.5.4   推荐! 2.6.5   推荐! 2.7  2.x  最后一个版本 3.x 3.1  不推荐,可以尝鲜 2to3 Help:  官网下载怎么打不开了? *  翻墙下载 *  http://code.google.com/p/smallfish   下载
目录结构 Windows DLLs Doc  Python 帮助, Pyer 必看! include Lib  Python 自带库的源码目录 site-packages  第三方库安装目录 libs Scripts  第三方库一些批处理和可执行的工具 tcl Tools LICENSE.txt NEWS.txt python.exe pythonw.exe README.txt …
优秀项目 Mercurial ( HG )  分布式版本控制系统 Twisted  网络编程框架 Trac  项目管理工具和 WIKI 系统 ReviewBoard  代码 review 工具 Sphinx  文档工具 SQLAlchemy  ORM  框架 Django 、 Pylons  WEB 开发框架 Stackless  山寨版 Python Google App Engine  平台 Cython  扩展工具
hello, world
语法特点 缩进 (建议 4 空格)  IndentationError 面向对象和面向过程 Pythonic  哲学,请参看: http://www.slideshare.net/nnfish/pythonic
代码截图
序列( 1 ) list >>> a = [1, 2, 3] >>>  print  a [1, 2, 3] >>>  print  a[0] 1 >>> a[2] = 10 >>>  print  a [1, 2, 10] tuple >>> b = (1, 2, 3) >>>  print   b, b[1] (1, 2, 3) 2 >>> b[1] = 20 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'tuple' object does not support item assignment
序列( 2 ) str >>> s = 'abcde' >>>  print  s abcde >>>  print  s[1] b >>> s[1] = 'd' Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'str' object does not support item assignment
序列切片 >>> a = 'abcd' >>>  print  a[1:3] bc >>>  print  a[1:] bcd >>>  print  a[:] abcd >>>  print  a[:3] abc >>>  print  a[:-1] abc >>>  print  a[-2] c 字符串反转 >>>  print  a[::-1] dcba a b c d 0 1 2 3 -4 -3 -2 -1
字典( 1 ) dict >>> c = {'name': 'smallfish', 'age': 20} >>>  print  c {'age': 20, 'name': 'smallfish'} >>>  print  c['name'] smallfish >>> c['name'] = 'chenxiaoyu' >>>  print  c {'age': 20, 'name': 'chenxiaoyu'} >>>  del  c['age'] >>>  print  c {'name': 'chenxiaoyu'} >>> c['address'] = 'China, Jiangsu' >>>  print  c {'name': 'chenxiaoyu', 'address': 'China, Jiangsu'}
字典( 2 ) 格式化输出 >>> c = {'name': 'smallfish', 'age': 20} >>> print &quot;hello %s, your age is %d&quot; % (c['name'], c['age']) hello smallfish, your age is 20 可以简单一点 >>> print &quot;hello %(name)s, your age is %(age)d&quot; % c hello smallfish, your age is 20
集合 set >>> a = set((1, 2, 3)) >>> b = set((2, 4, 6)) >>>  print  a set([1, 2, 3]) >>> print a, b set([1, 2, 3]) set([2, 4, 6]) >>>  print  a & b set([2])v >>>  print  a | b set([1, 2, 3, 4, 6]) >>>  print  a ^ b set([1, 3, 4, 6]) 去除某数组内重复数据 a = ['aaa', 'bbb', 'ccc', 'aaa', 'ddd', 'aaa'] >>> list(set(a))  ['aaa', 'bbb', 'ccc', 'ddd']
流程控制 if  a == 1: print  'aaa' else : print  'bbb' if  b == 1: print  '111' elif  b == 2: print   '222' else : print  '000' while  a < 10: print  a a += 1  for   item  in  (1, 2, 3): print  item d = {'name': 'smallfish', 'age': 20} for  k  in  d: print  k, d[k] for  k, v  in  d.items(): print  k, v 输出 age 20 name smallfish
函数( 1 ) def  hello(name): &quot;hello function, name is param&quot; print  &quot;hello&quot;, name >>>  print  hello.__doc__ hello function, name is param >>> hello('smallfish') hello smallfish #  给函数参数加默认值 def  hello(name='smallfish'): #  同上代码 >>> hello() hello smallfish >>> hello('chenxiaoyu') hello chenxiaoyu
函数( 2 ) #  不定参数 def  hello(*args, **kwargs): print  args print  kwargs >>> hello() () {} >>> hello(1, 2, 3) (1, 2, 3) {} >>> hello(1, 2, 3, a='aa', b='bb') (1, 2, 3) {'a': 'aa', 'b': 'bb'} >>>
函数( 3 ) lambda 函数 简单函数: def lowercase(x): return x.lower() 其实可以这么写: lowercase = lambda x: x.lower()
内置函数 >>>  help(re) Help on module re: NAME re - Support for regular expressions (RE). FILE d:\python27\lib\re.py DESCRIPTION … >>>  dir(re) ['DEBUG', 'DOTALL', ..., 'sys', 'template'] >>>  globals() {'a': 'abcd', '__builtins__': <module '__builtin__' (built-in)> … } locals() vars()  输出基本同上 >>>  type(re) <type 'module'> >>>  type('aa') <type 'str'>
Class class  User: def  __init__(self, name): self.name = name def  get_name(self): return self.name >>> u = User('smallfish') >>>  print  u.get_name() smallfish
模块 # user.py def  hello(name): print  'hello', name class  User: def  __init__(self, name): self.name = name def  get_name(self): return self.name >>>  import  user >>>  dir (user) ['User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello'] >>> user.hello('smallfish') hello smallfish >>> u = user.User('smallfish') >>>  print  u.get_name() smallfish
列表推导 L ist  C omprehension (适用于 dict , tuple , str ) 过滤数组中除以 2 等于 0 的元素: tmp = [] items = [1, 2, 3, 4, 5] for i in items: if i % 2 == 0: tmp.append(i) #  其实可以这么做: >>> [item  for  item  in  items  if  item % 2 == 0] [2, 4] #  每个元素都乘以 2 >>> [item * 2  for  item  in  items] [2, 4, 6, 8, 10]
修饰器( 1 ) Decorator , Python2.4 之后新加特性! 问题:想记录每个函数执行多少时间? def hello():   start = time.time() …  run code print time.time() – start 是不是太丑了点?用修饰器吧。 先写一个包装函数: def time_wrapper(func): def _wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) print func.__name__, time.time() – start return _wrapper
修饰器( 2 ) 测试函数: def hello(n): sum = 0 for i in range(n): sum += I return sum 我们可以这样调用: a = time_wrapper(hello) print a(100) 这个不稀奇,还可以这样写: @time_wrapper def hello(n): …  同上 >>> hello(1000000) hello 0.265000104904
示例代码( 1 ) 交换值 1) tmp = a a = b b = tmp 2) a, b = b, a 判断 key 是否在 dict 中 1) if d.has_key(key): 2) if key in d:
示例代码( 2 ) 数组转字典 name = [&quot;smallfish&quot;, &quot;user_a&quot;, &quot;user_b&quot;] city = [&quot;hangzhou&quot;, &quot;nanjing&quot;, &quot;beijing&quot;] print  dict(zip(name, city)) {'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'} 还需要两次 for 循环么? 输出文件 with open(&quot;d:/1.log&quot;) as fp: line = fp.readline() print line
示例代码( 3 ) 数据库操作 >>> import psycopg2 >>> db = psycopg2.connect(&quot;host=localhost user=smallfish password=xx dbname=test&quot;) >>> cursor = db.cursor() >>> cursor.execute('select version()') >>> print cursor.fetchall() [('PostgreSQL 8.4.4 on i486-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debian 4.4.4-7) 4.4.4, 32-bit',)] >>> cursor.close() >>> db.close()
其他资源 《 A Byte of Python 》(中文名: Python 简明教程) 《 Python Tutorial 》( Python 官方手册,必读啊!) 《  Python Style PEP-0008 》 http://www.python.org/dev/peps/pep-0008/ 《 Pythonic 》(更多有趣的写法)  http://www.slideshare.net/nnfish/pythonic
结束 print   &quot; Thanks! &quot; import  sys sys.exit(0)

More Related Content

PPT
Shell脚本
 
PDF
PPTX
从问题开始,谈前端架构
PPTX
Bash shell script 教學
PDF
Python basic - v01
PDF
JavaScript 快速複習 2017Q1
PPTX
Python入門:5大概念初心者必備 2021/11/18
PDF
Ch8 教學
Shell脚本
 
从问题开始,谈前端架构
Bash shell script 教學
Python basic - v01
JavaScript 快速複習 2017Q1
Python入門:5大概念初心者必備 2021/11/18
Ch8 教學

What's hot (20)

PPTX
Python入門:5大概念初心者必備
PDF
Python 于 webgame 的应用
PDF
Ch7 範例
DOC
中心教员Java面试题1
PDF
PPT
Python Basic
PDF
Ch10 範例
PDF
Ch10 教學
PDF
Ch4 教學
PDF
Ch7 教學
PDF
论 Python 与设计模式。
PDF
Ch5 教學
PDF
Python速成指南
PPT
页游开发中的 Python 组件与模式
PDF
Ch12 教學
PDF
Ch9 教學
PPT
基于XMPP的Gtalk机器人
PDF
手把手打開Python資料分析大門
PDF
PPT
Python实现协同过滤
Python入門:5大概念初心者必備
Python 于 webgame 的应用
Ch7 範例
中心教员Java面试题1
Python Basic
Ch10 範例
Ch10 教學
Ch4 教學
Ch7 教學
论 Python 与设计模式。
Ch5 教學
Python速成指南
页游开发中的 Python 组件与模式
Ch12 教學
Ch9 教學
基于XMPP的Gtalk机器人
手把手打開Python資料分析大門
Python实现协同过滤
Ad

Viewers also liked (6)

KEY
Saving Gaia with GeoDjango
PPTX
Desenvolvimento de aplicações geográficas utilizando Django/Geodjango
PPTX
KISD E-Rate Overview
KEY
zhng your vim
KEY
Django101 geodjango
PPTX
Pythonic
Saving Gaia with GeoDjango
Desenvolvimento de aplicações geográficas utilizando Django/Geodjango
KISD E-Rate Overview
zhng your vim
Django101 geodjango
Pythonic
Ad

Similar to Python story (20)

ODP
Op 20090411
PPT
Python 入门
PPT
Javascript Training
PDF
竞赛中C++语言拾遗
PPT
如何学习Bash Shell
PPT
数据处理算法设计要点
ODP
Ruby程式語言入門導覽
PPT
Mongo快速入门
PPTX
Python入门
ODP
patch和diff
PDF
20240921 - HITCON 社群活動 - 《HITCON CTF 甘苦談》
PDF
張逸 - 研究所 / 轉學考計算機概論 、公職計算機概要 - 程式語言 - 試閱版
PPT
搜狐Pv insight(py)技术交流
 
PPT
搜狐Pv insight(py)技术交流
DOC
Free Marker中文文档
PPT
ajax_onlinemad
PPT
Mongodb
 
PPT
dspch01資料結構資料結構資料結構資料結構資料結構資料結構資料結構資料結構.ppt
PPT
第5章数组
PDF
Practical Data Analysis in R
Op 20090411
Python 入门
Javascript Training
竞赛中C++语言拾遗
如何学习Bash Shell
数据处理算法设计要点
Ruby程式語言入門導覽
Mongo快速入门
Python入门
patch和diff
20240921 - HITCON 社群活動 - 《HITCON CTF 甘苦談》
張逸 - 研究所 / 轉學考計算機概論 、公職計算機概要 - 程式語言 - 試閱版
搜狐Pv insight(py)技术交流
 
搜狐Pv insight(py)技术交流
Free Marker中文文档
ajax_onlinemad
Mongodb
 
dspch01資料結構資料結構資料結構資料結構資料結構資料結構資料結構資料結構.ppt
第5章数组
Practical Data Analysis in R

Python story

  • 1. Python Story 陈小玉 <smallfish.xy@gmail.com> twitter: @nnfish blog: http://chenxiaoyu.org
  • 2. 历史由来 阿姆斯特丹 1989 年圣诞节期间 Guido van Rossum 为了打发圣诞节的无趣 决心开发一种新的解释性程序 … 不久之后,一个叫 Python 的语言就诞生了! 注: Guido 又称龟叔或者莽爹 :_)
  • 3. 能做什么 系统编程 GUI 应用 网络应用 数据库应用 WEB 应用 快速开发模型 游戏、人工智能、图像等 … more
  • 4. 谁在用 Google YouTube Bittorrent Facebook Digg Dropbox Opera Reddit Sourceforge 豆瓣 搜狐邮箱 金山 … more
  • 5. 优势 免费、开源 跨平台 简单易学 快速开发 类库丰富 易扩展 可嵌入性
  • 6. 版本信息 2.x 2.5.4 推荐! 2.6.5 推荐! 2.7 2.x 最后一个版本 3.x 3.1 不推荐,可以尝鲜 2to3 Help: 官网下载怎么打不开了? * 翻墙下载 * http://code.google.com/p/smallfish 下载
  • 7. 目录结构 Windows DLLs Doc Python 帮助, Pyer 必看! include Lib Python 自带库的源码目录 site-packages 第三方库安装目录 libs Scripts 第三方库一些批处理和可执行的工具 tcl Tools LICENSE.txt NEWS.txt python.exe pythonw.exe README.txt …
  • 8. 优秀项目 Mercurial ( HG ) 分布式版本控制系统 Twisted 网络编程框架 Trac 项目管理工具和 WIKI 系统 ReviewBoard 代码 review 工具 Sphinx 文档工具 SQLAlchemy ORM 框架 Django 、 Pylons WEB 开发框架 Stackless 山寨版 Python Google App Engine 平台 Cython 扩展工具
  • 10. 语法特点 缩进 (建议 4 空格) IndentationError 面向对象和面向过程 Pythonic 哲学,请参看: http://www.slideshare.net/nnfish/pythonic
  • 12. 序列( 1 ) list >>> a = [1, 2, 3] >>> print a [1, 2, 3] >>> print a[0] 1 >>> a[2] = 10 >>> print a [1, 2, 10] tuple >>> b = (1, 2, 3) >>> print b, b[1] (1, 2, 3) 2 >>> b[1] = 20 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'tuple' object does not support item assignment
  • 13. 序列( 2 ) str >>> s = 'abcde' >>> print s abcde >>> print s[1] b >>> s[1] = 'd' Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'str' object does not support item assignment
  • 14. 序列切片 >>> a = 'abcd' >>> print a[1:3] bc >>> print a[1:] bcd >>> print a[:] abcd >>> print a[:3] abc >>> print a[:-1] abc >>> print a[-2] c 字符串反转 >>> print a[::-1] dcba a b c d 0 1 2 3 -4 -3 -2 -1
  • 15. 字典( 1 ) dict >>> c = {'name': 'smallfish', 'age': 20} >>> print c {'age': 20, 'name': 'smallfish'} >>> print c['name'] smallfish >>> c['name'] = 'chenxiaoyu' >>> print c {'age': 20, 'name': 'chenxiaoyu'} >>> del c['age'] >>> print c {'name': 'chenxiaoyu'} >>> c['address'] = 'China, Jiangsu' >>> print c {'name': 'chenxiaoyu', 'address': 'China, Jiangsu'}
  • 16. 字典( 2 ) 格式化输出 >>> c = {'name': 'smallfish', 'age': 20} >>> print &quot;hello %s, your age is %d&quot; % (c['name'], c['age']) hello smallfish, your age is 20 可以简单一点 >>> print &quot;hello %(name)s, your age is %(age)d&quot; % c hello smallfish, your age is 20
  • 17. 集合 set >>> a = set((1, 2, 3)) >>> b = set((2, 4, 6)) >>> print a set([1, 2, 3]) >>> print a, b set([1, 2, 3]) set([2, 4, 6]) >>> print a & b set([2])v >>> print a | b set([1, 2, 3, 4, 6]) >>> print a ^ b set([1, 3, 4, 6]) 去除某数组内重复数据 a = ['aaa', 'bbb', 'ccc', 'aaa', 'ddd', 'aaa'] >>> list(set(a)) ['aaa', 'bbb', 'ccc', 'ddd']
  • 18. 流程控制 if a == 1: print 'aaa' else : print 'bbb' if b == 1: print '111' elif b == 2: print '222' else : print '000' while a < 10: print a a += 1 for item in (1, 2, 3): print item d = {'name': 'smallfish', 'age': 20} for k in d: print k, d[k] for k, v in d.items(): print k, v 输出 age 20 name smallfish
  • 19. 函数( 1 ) def hello(name): &quot;hello function, name is param&quot; print &quot;hello&quot;, name >>> print hello.__doc__ hello function, name is param >>> hello('smallfish') hello smallfish # 给函数参数加默认值 def hello(name='smallfish'): # 同上代码 >>> hello() hello smallfish >>> hello('chenxiaoyu') hello chenxiaoyu
  • 20. 函数( 2 ) # 不定参数 def hello(*args, **kwargs): print args print kwargs >>> hello() () {} >>> hello(1, 2, 3) (1, 2, 3) {} >>> hello(1, 2, 3, a='aa', b='bb') (1, 2, 3) {'a': 'aa', 'b': 'bb'} >>>
  • 21. 函数( 3 ) lambda 函数 简单函数: def lowercase(x): return x.lower() 其实可以这么写: lowercase = lambda x: x.lower()
  • 22. 内置函数 >>> help(re) Help on module re: NAME re - Support for regular expressions (RE). FILE d:\python27\lib\re.py DESCRIPTION … >>> dir(re) ['DEBUG', 'DOTALL', ..., 'sys', 'template'] >>> globals() {'a': 'abcd', '__builtins__': <module '__builtin__' (built-in)> … } locals() vars() 输出基本同上 >>> type(re) <type 'module'> >>> type('aa') <type 'str'>
  • 23. Class class User: def __init__(self, name): self.name = name def get_name(self): return self.name >>> u = User('smallfish') >>> print u.get_name() smallfish
  • 24. 模块 # user.py def hello(name): print 'hello', name class User: def __init__(self, name): self.name = name def get_name(self): return self.name >>> import user >>> dir (user) ['User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello'] >>> user.hello('smallfish') hello smallfish >>> u = user.User('smallfish') >>> print u.get_name() smallfish
  • 25. 列表推导 L ist C omprehension (适用于 dict , tuple , str ) 过滤数组中除以 2 等于 0 的元素: tmp = [] items = [1, 2, 3, 4, 5] for i in items: if i % 2 == 0: tmp.append(i) # 其实可以这么做: >>> [item for item in items if item % 2 == 0] [2, 4] # 每个元素都乘以 2 >>> [item * 2 for item in items] [2, 4, 6, 8, 10]
  • 26. 修饰器( 1 ) Decorator , Python2.4 之后新加特性! 问题:想记录每个函数执行多少时间? def hello(): start = time.time() … run code print time.time() – start 是不是太丑了点?用修饰器吧。 先写一个包装函数: def time_wrapper(func): def _wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) print func.__name__, time.time() – start return _wrapper
  • 27. 修饰器( 2 ) 测试函数: def hello(n): sum = 0 for i in range(n): sum += I return sum 我们可以这样调用: a = time_wrapper(hello) print a(100) 这个不稀奇,还可以这样写: @time_wrapper def hello(n): … 同上 >>> hello(1000000) hello 0.265000104904
  • 28. 示例代码( 1 ) 交换值 1) tmp = a a = b b = tmp 2) a, b = b, a 判断 key 是否在 dict 中 1) if d.has_key(key): 2) if key in d:
  • 29. 示例代码( 2 ) 数组转字典 name = [&quot;smallfish&quot;, &quot;user_a&quot;, &quot;user_b&quot;] city = [&quot;hangzhou&quot;, &quot;nanjing&quot;, &quot;beijing&quot;] print dict(zip(name, city)) {'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'} 还需要两次 for 循环么? 输出文件 with open(&quot;d:/1.log&quot;) as fp: line = fp.readline() print line
  • 30. 示例代码( 3 ) 数据库操作 >>> import psycopg2 >>> db = psycopg2.connect(&quot;host=localhost user=smallfish password=xx dbname=test&quot;) >>> cursor = db.cursor() >>> cursor.execute('select version()') >>> print cursor.fetchall() [('PostgreSQL 8.4.4 on i486-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debian 4.4.4-7) 4.4.4, 32-bit',)] >>> cursor.close() >>> db.close()
  • 31. 其他资源 《 A Byte of Python 》(中文名: Python 简明教程) 《 Python Tutorial 》( Python 官方手册,必读啊!) 《 Python Style PEP-0008 》 http://www.python.org/dev/peps/pep-0008/ 《 Pythonic 》(更多有趣的写法) http://www.slideshare.net/nnfish/pythonic
  • 32. 结束 print &quot; Thanks! &quot; import sys sys.exit(0)