02.python基础
TRANSCRIPT
Python开发初步
Python运行环境
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
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
交互方式
命令行
GUI
python program.py
先编译后运行 .pyc, .pyo
建议将python和python/Scripts设置到PATH环境变量中。
嵌入运行方式,可以在C/C++中调用python代码。在jython中调用java和python代码。
import this
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!
Hello, python
>>> print “hello, python”
Hello, python
python hello.py
Too Simple?
特性概述
• 缩近是一种语法要求,缩近块以’:’结束• #开头的是注释。无多行注释
• 无行结束符,以自然行结束。对于有括号的可以是多行。如:[], (), {}
• 一切皆对象• Class不是必须的• 动态类型,强类型,赋值时绑定• 垃圾自动回收• 自省能力• 内置多样的数据类型:list, tuple, dict, set等• 支持可变参数• 支持异常和执行栈
程序组织
• Python文件
• 包 (一个目录,下面有__init__.py)
import
• 通过import来导入模块
• 通过from module import xxx来导入module中的对象,使用 ‘*’ 表示所全对象
• 控制导出内容,可以在被导出模块中添加:
__all__ = [‘name1’, ‘name2’,…]
• 通过__import__来动态导入
• 导入路径:sys.path
Python执行
• 交互式执行
• 解释执行
• 先编译后执行
• 模块顶层代码会在导入时被执行
• 不会重复导入
• reload(module)可以重新装入一个模块
• 通过判断 if __name__ == ‘__main__’来区分是主程序还是导入模块
• 内置变量:__path__, __file__
基本数据类型
• 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()
整数
• int
1 (10进制)
0x1 (16进制)
07 (8进制)
int(xxx)
• Long
Nl, NL
long(xxx)
浮点数
• 1.0
• 1.0e+2
• float(xxx)
字符串
• ‘xxx’ 单引号
• “xxx” 双引号
• “””abccde””” 三重引号
• 转义 ‘\n’, ‘\t’, ‘\xa3’
• raw string r’a\n’
• 编码:gbk, utf8
• str(x)
unicode
• u'\u4e2d\u56fd‘
• 在源文件中与#coding=xxx配合,可以使用u’xxx’来定义unicode
• 3.X内部为unicode,2.X内部为str
• unicode(‘xxx’)
list
• []
• [‘a’, ‘b’, 1, 2]
• [x for x in aList] -- list comprehension
• [:] 复制
• [1:2] 分片
• [begin:end:step]
tuple
• ()
• (1,) 单元素tuple
• (1,2,…) 多元素
• tuple(list)
• 打包和拆包:a, b = b, a
return a, b
a, b = aTuple
a = 1, 2
set
• set()
• {…} {}不是set是dict
• set([sequence])
• {x for x in range(10)}
dict
• {}
• {key1:value1, key2:value2,…}
• {k: v for k, v in [('a', 1),('b', 2)]}
• 无序
• >>> from collections import OrderedDict
bool
• bool(xxx)
• True
• False
程序结构
• 注释(#开头)• 普通语句:
– 赋值语句– 声明语句– 执行语句
• 块语句:– If/elif/else– with– while– def– class– for– try/finally/except
• 逻辑行:自然行,括号可以多行,三重引号• ;可以连接短句 a=1;c=2
表达式
• 对象 op 对象
• 当对象不一致时,会自动进行类型转換
• 有些类型是不能互转的,如int不能转为str
• 存在float将转为float,存在unicode将转为unicode
算术运算
• +=, -=, *=, /=
• +, -
• *, /, //, %, **, <<, >>
• ~, &, |
• 使用括号改变优先级
• 无++语法
算术比较
• ==
• !=
• >
• <
• >=
• <=
• a<b<c
逻辑运算
• and
• or
• not
• a = 5 if b> 3 else 4
• a = c or ‘default’
• a = c and ‘default’
• 短路逻辑
• 所有空值为假
特殊运算
• in
>>> 1 in [1,2,3]
True
>>> 1 in {1:’a’}
True
变量/赋值语句
• a = 2• b = A()• a = b = ‘2’• 变量是先声明再使用• 强类型• 变量在3.X可以是unicode字符串• 变量是绑定方式• 对象采用引用计数方式• del 变量
声明语句
• global
• nonlocal(3.X)
执行语句
• 函数调用
• 对象调用
• 示例:
– print #3.X改为函数
– exec #3.X改为函数
– pass #空语句
– assert #断言
块语句
• 块语句以’:’结束
• 块语句可以嵌套,不同的嵌套以不同的缩近级别表示
• 建议使用空格为缩近
• 常见块语句关键字:if/elif/else, def, while, with, for, class,try/except/finally
判断语句
if 表达式:
#执行语句
elif 表达式:
#执行语句
else:
#执行语句
循环语句
for x in iterator:#执行代码continuebreak
else:#循环未执行时的代码
while 表达式:
#执行代码
break
函数定义
def ():
#执行代码
return
def (name):
def (name, *args, **kwargs): #可变参数
def (name=‘abc’): #缺省参数
#无return时返回None
函数使用常见问题(1)-可变初始值
>>> def f(a=[]):
… a.append(‘1’)
… return a
>>> b = f()
[‘1’]
>>> c = f()
[‘1’, ‘1’]
#因为初始值在函数导入时初始化一次,因此它的值会一直保留下来
函数使用常见问题(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可以声明全局变量
异常处理
try:
f = open(‘a.txt’)
except Exception as e:
#process
finally:
#process
异常捕捉
多异常捕捉
try:
f = open(‘a.txt’)
except (TypeError, ValueError):
#process
finally:
#process
引发异常
• raise Exception(args)
异常树
-BaseException|- KeyboardInterrupt|- SystemExit|- Exception
|- (all other current built-in exceptions)
自定义异常
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value) ...
内置函数
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()
常用模块beterries included
• os, sys 操作系统相关
• re 正则表达式
• math 数学计算
• urllib2, smtplib, httplib, ftplib 网络操作
• datetime, time 时间
• thread, theading 线程
• decimal
第三方库
• 集中在pypi上(http://pypi.python.org/pypi)
• 通过pip来安装
例如:
pip install uliweb
Python参考
•Dive Into Python•A Byte of Python•Python Tutorial•Learning Python•可爱的Python•Python核心编程
如何学习?
• 实践是检验真理的唯一标准• 学习/体验自由精神• 强调钻研精神• 强调知识的分享• 在工作和学习中主动应用• 订阅邮件列表与人交流(python-cn)• 参与项目• 多看源代码• 勤写作、勤积累
坚持!
Q&A