02.python基础
TRANSCRIPT
![Page 2: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/2.jpg)
Python开发初步
![Page 3: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/3.jpg)
Python运行环境
![Page 4: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/4.jpg)
![Page 5: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/5.jpg)
Kivy
from kivy.app import App from kivy.uix.button import Button
class TestApp(App): def build(self): return Button(text='Hello World')
TestApp().run()
Kivy – 进行快速应用开发的开源Python库,用来构建革新性的用户界面,如多触点应用。
• Linux• Windows• MacOSX• Android• IOS
![Page 6: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/6.jpg)
pyjnius
>>> from jnius import autoclass>>> autoclass('java.lang.System').out.println('Hello world') Hello world >>> Stack = autoclass('java.util.Stack') >>> stack = Stack() >>> stack.push('hello') >>> stack.push('world') >>> print stack.pop() world >>> print stack.pop() hello
![Page 7: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/7.jpg)
交互方式
命令行
GUI
![Page 8: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/8.jpg)
python program.py
先编译后运行 .pyc, .pyo
建议将python和python/Scripts设置到PATH环境变量中。
![Page 9: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/9.jpg)
嵌入运行方式,可以在C/C++中调用python代码。在jython中调用java和python代码。
![Page 10: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/10.jpg)
import this
![Page 11: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/11.jpg)
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
![Page 12: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/12.jpg)
Hello, python
![Page 13: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/13.jpg)
>>> print “hello, python”
Hello, python
python hello.py
![Page 14: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/14.jpg)
Too Simple?
![Page 15: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/15.jpg)
![Page 16: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/16.jpg)
特性概述
![Page 17: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/17.jpg)
• 缩近是一种语法要求,缩近块以’:’结束• #开头的是注释。无多行注释
• 无行结束符,以自然行结束。对于有括号的可以是多行。如:[], (), {}
• 一切皆对象• Class不是必须的• 动态类型,强类型,赋值时绑定• 垃圾自动回收• 自省能力• 内置多样的数据类型:list, tuple, dict, set等• 支持可变参数• 支持异常和执行栈
![Page 18: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/18.jpg)
程序组织
• Python文件
• 包 (一个目录,下面有__init__.py)
![Page 19: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/19.jpg)
import
• 通过import来导入模块
• 通过from module import xxx来导入module中的对象,使用 ‘*’ 表示所全对象
• 控制导出内容,可以在被导出模块中添加:
__all__ = [‘name1’, ‘name2’,…]
• 通过__import__来动态导入
• 导入路径:sys.path
![Page 20: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/20.jpg)
Python执行
• 交互式执行
• 解释执行
• 先编译后执行
• 模块顶层代码会在导入时被执行
• 不会重复导入
• reload(module)可以重新装入一个模块
• 通过判断 if __name__ == ‘__main__’来区分是主程序还是导入模块
• 内置变量:__path__, __file__
![Page 21: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/21.jpg)
基本数据类型
• int, long, bin, str, unicode, float, dict, tuple, list, set, complex
基本类型
• int, long, bin, float, str, unicode, tuple, complex
不可变类型
• dict, list, set可变类型
• list, tuple, set, str, unicode序列
• dict映射
转换str(), float()…反射类型 type()
![Page 22: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/22.jpg)
整数
• int
1 (10进制)
0x1 (16进制)
07 (8进制)
int(xxx)
• Long
Nl, NL
long(xxx)
![Page 23: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/23.jpg)
浮点数
• 1.0
• 1.0e+2
• float(xxx)
![Page 24: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/24.jpg)
字符串
• ‘xxx’ 单引号
• “xxx” 双引号
• “””abccde””” 三重引号
• 转义 ‘\n’, ‘\t’, ‘\xa3’
• raw string r’a\n’
• 编码:gbk, utf8
• str(x)
![Page 25: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/25.jpg)
unicode
• u'\u4e2d\u56fd‘
• 在源文件中与#coding=xxx配合,可以使用u’xxx’来定义unicode
• 3.X内部为unicode,2.X内部为str
• unicode(‘xxx’)
![Page 26: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/26.jpg)
list
• []
• [‘a’, ‘b’, 1, 2]
• [x for x in aList] -- list comprehension
• [:] 复制
• [1:2] 分片
• [begin:end:step]
![Page 27: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/27.jpg)
tuple
• ()
• (1,) 单元素tuple
• (1,2,…) 多元素
• tuple(list)
• 打包和拆包:a, b = b, a
return a, b
a, b = aTuple
a = 1, 2
![Page 28: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/28.jpg)
set
• set()
• {…} {}不是set是dict
• set([sequence])
• {x for x in range(10)}
![Page 29: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/29.jpg)
dict
• {}
• {key1:value1, key2:value2,…}
• {k: v for k, v in [('a', 1),('b', 2)]}
• 无序
• >>> from collections import OrderedDict
![Page 30: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/30.jpg)
bool
• bool(xxx)
• True
• False
![Page 31: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/31.jpg)
程序结构
![Page 32: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/32.jpg)
• 注释(#开头)• 普通语句:
– 赋值语句– 声明语句– 执行语句
• 块语句:– If/elif/else– with– while– def– class– for– try/finally/except
• 逻辑行:自然行,括号可以多行,三重引号• ;可以连接短句 a=1;c=2
![Page 33: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/33.jpg)
表达式
• 对象 op 对象
• 当对象不一致时,会自动进行类型转換
• 有些类型是不能互转的,如int不能转为str
• 存在float将转为float,存在unicode将转为unicode
![Page 34: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/34.jpg)
算术运算
• +=, -=, *=, /=
• +, -
• *, /, //, %, **, <<, >>
• ~, &, |
• 使用括号改变优先级
• 无++语法
![Page 35: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/35.jpg)
算术比较
• ==
• !=
• >
• <
• >=
• <=
• a<b<c
![Page 36: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/36.jpg)
逻辑运算
• and
• or
• not
• a = 5 if b> 3 else 4
• a = c or ‘default’
• a = c and ‘default’
• 短路逻辑
• 所有空值为假
![Page 37: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/37.jpg)
特殊运算
• in
>>> 1 in [1,2,3]
True
>>> 1 in {1:’a’}
True
![Page 38: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/38.jpg)
变量/赋值语句
• a = 2• b = A()• a = b = ‘2’• 变量是先声明再使用• 强类型• 变量在3.X可以是unicode字符串• 变量是绑定方式• 对象采用引用计数方式• del 变量
![Page 39: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/39.jpg)
声明语句
• global
• nonlocal(3.X)
![Page 40: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/40.jpg)
执行语句
• 函数调用
• 对象调用
• 示例:
– print #3.X改为函数
– exec #3.X改为函数
– pass #空语句
– assert #断言
![Page 41: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/41.jpg)
块语句
• 块语句以’:’结束
• 块语句可以嵌套,不同的嵌套以不同的缩近级别表示
• 建议使用空格为缩近
• 常见块语句关键字:if/elif/else, def, while, with, for, class,try/except/finally
![Page 42: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/42.jpg)
判断语句
if 表达式:
#执行语句
elif 表达式:
#执行语句
else:
#执行语句
![Page 43: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/43.jpg)
循环语句
for x in iterator:#执行代码continuebreak
else:#循环未执行时的代码
while 表达式:
#执行代码
break
![Page 44: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/44.jpg)
函数定义
def ():
#执行代码
return
def (name):
def (name, *args, **kwargs): #可变参数
def (name=‘abc’): #缺省参数
#无return时返回None
![Page 45: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/45.jpg)
函数使用常见问题(1)-可变初始值
>>> def f(a=[]):
… a.append(‘1’)
… return a
>>> b = f()
[‘1’]
>>> c = f()
[‘1’, ‘1’]
#因为初始值在函数导入时初始化一次,因此它的值会一直保留下来
![Page 46: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/46.jpg)
函数使用常见问题(2)-作用域
>>> a = 1… def f(n):… a = n + 1… return a>>> f(2)3>>> a1
变量有作用域,下一层可以使用上一层的变量,一旦赋值将会在当前作用域创建新的变量
>>> a = 1… def f(n):… global a… a = n + 1… return a>>> f(2)3>>> a3
使用global可以声明全局变量
![Page 47: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/47.jpg)
异常处理
![Page 48: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/48.jpg)
try:
f = open(‘a.txt’)
except Exception as e:
#process
finally:
#process
异常捕捉
![Page 49: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/49.jpg)
多异常捕捉
try:
f = open(‘a.txt’)
except (TypeError, ValueError):
#process
finally:
#process
![Page 50: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/50.jpg)
引发异常
• raise Exception(args)
![Page 51: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/51.jpg)
异常树
-BaseException|- KeyboardInterrupt|- SystemExit|- Exception
|- (all other current built-in exceptions)
![Page 52: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/52.jpg)
自定义异常
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value) ...
![Page 53: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/53.jpg)
内置函数
![Page 54: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/54.jpg)
Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set() apply()
delattr() help() next() setattr() buffer()
dict() hex() object() slice() coerce()
dir() id() oct() sorted() intern()
![Page 55: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/55.jpg)
常用模块beterries included
![Page 56: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/56.jpg)
• os, sys 操作系统相关
• re 正则表达式
• math 数学计算
• urllib2, smtplib, httplib, ftplib 网络操作
• datetime, time 时间
• thread, theading 线程
• decimal
![Page 57: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/57.jpg)
第三方库
![Page 58: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/58.jpg)
• 集中在pypi上(http://pypi.python.org/pypi)
• 通过pip来安装
例如:
pip install uliweb
![Page 59: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/59.jpg)
Python参考
![Page 60: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/60.jpg)
![Page 61: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/61.jpg)
•Dive Into Python•A Byte of Python•Python Tutorial•Learning Python•可爱的Python•Python核心编程
![Page 62: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/62.jpg)
如何学习?
• 实践是检验真理的唯一标准• 学习/体验自由精神• 强调钻研精神• 强调知识的分享• 在工作和学习中主动应用• 订阅邮件列表与人交流(python-cn)• 参与项目• 多看源代码• 勤写作、勤积累
![Page 63: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/63.jpg)
坚持!
![Page 64: 02.python基础](https://reader030.vdocuments.pub/reader030/viewer/2022012403/55ab13021a28ab2a698b487c/html5/thumbnails/64.jpg)
Q&A