SlideShare a Scribd company logo
基础
limodou@gmail.com
Python开发初步
Python运行环境
02.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?
02.python基础
特性概述
• 缩近是一种语法要求,缩近块以’:’结束
• #开头的是注释。无多行注释
• 无行结束符,以自然行结束。对于有括号的可
以是多行。如:[], (), {}
• 一切皆对象
• 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” 双引号
• “””abc
cde””” 三重引号
• 转义 ‘n’, ‘t’, ‘xa3’
• raw string r’an’
• 编码:gbk, utf8
• str(x)
unicode
• u'u4e2du56fd‘
• 在源文件中与#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:
#执行代码
continue
break
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
>>> a
1
变量有作用域,下一层可
以使用上一层的变量,
一旦赋值将会在当前作
用域创建新的变量
>>> a = 1
… def f(n):
… global a
… a = n + 1
… return a
>>> f(2)
3
>>> a
3
使用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参考
02.python基础
•Dive Into Python
•A Byte of Python
•Python Tutorial
•Learning Python
•可爱的Python
•Python核心编程
如何学习?
• 实践是检验真理的唯一标准
• 学习/体验 自由精神
• 强调钻研精神
• 强调知识的分享
• 在工作和学习中主动应用
• 订阅邮件列表与人交流(python-cn)
• 参与项目
• 多看源代码
• 勤写作、勤积累
坚持!
Q&A

More Related Content

PDF
compiler fuzzer : prog fuzz介紹
PPT
常用Mac/Linux命令分享
PPTX
12, string
PDF
Mac os Terminal 常用指令與小技巧
PPTX
Some tips
PPT
页游开发中的 Python 组件与模式
PDF
Shell(bash) Scripting
PDF
论 Python 与设计模式。
compiler fuzzer : prog fuzz介紹
常用Mac/Linux命令分享
12, string
Mac os Terminal 常用指令與小技巧
Some tips
页游开发中的 Python 组件与模式
Shell(bash) Scripting
论 Python 与设计模式。

What's hot (20)

PDF
PDF
型態與運算子
PDF
Command line 初級寶典
PDF
Python 于 webgame 的应用
PDF
Ceph中国社区9.19 Ceph IO 路径 和性能分析-王豪迈05
PDF
Python 2 - 快速簡介
PDF
Learning python in the motion picture industry by will zhou
PDF
Vim Hacks
PPTX
C++11综述/新特性描述/Overview of C++11 New Features
ODP
新北市教師工作坊 -- Bash script programming 介紹
PDF
從 REPL 到 IDE
PPTX
例外處理
PPT
Device Driver - Chapter 3字元驅動程式
PDF
流程語法與函式
PPT
Python 入门
PDF
那些年,我們一起看的例外
PDF
S1: InnoDB AIO原理及相关bug分析
PDF
[圣思园][Java SE]Jdk5
PDF
shell script introduction
PDF
Ooredis
型態與運算子
Command line 初級寶典
Python 于 webgame 的应用
Ceph中国社区9.19 Ceph IO 路径 和性能分析-王豪迈05
Python 2 - 快速簡介
Learning python in the motion picture industry by will zhou
Vim Hacks
C++11综述/新特性描述/Overview of C++11 New Features
新北市教師工作坊 -- Bash script programming 介紹
從 REPL 到 IDE
例外處理
Device Driver - Chapter 3字元驅動程式
流程語法與函式
Python 入门
那些年,我們一起看的例外
S1: InnoDB AIO原理及相关bug分析
[圣思园][Java SE]Jdk5
shell script introduction
Ooredis
Ad

Similar to 02.python基础 (20)

PDF
模块一-Go语言特性.pdf
PDF
Clojure
PDF
Java Jdk6学习笔记[Ppt]
PDF
看似比較簡單的推坑教學 C語言從崩潰到崩潰Ex(二)
PPTX
Python 入門
PDF
Python速成指南
PDF
Python学习笔记
PDF
Python 温故
PPTX
IOS入门分享
PDF
Introduce to Linux command line
PPTX
Angular 开发技巧 (2018 ngChina 开发者大会)
PPT
第9章 Shell 編程
PDF
getPDF.aspx
PDF
getPDF.aspx
PDF
[圣思园][Java SE]Io 3
PDF
Clojure简介与应用
PPTX
Study4.TW .NET Conf 2018 - Fp in c#
PDF
The Evolution of Async Programming (GZ TechParty C#)
PPT
Python 脚本入门基础
PPTX
Python入門:5大概念初心者必備 2021/11/18
模块一-Go语言特性.pdf
Clojure
Java Jdk6学习笔记[Ppt]
看似比較簡單的推坑教學 C語言從崩潰到崩潰Ex(二)
Python 入門
Python速成指南
Python学习笔记
Python 温故
IOS入门分享
Introduce to Linux command line
Angular 开发技巧 (2018 ngChina 开发者大会)
第9章 Shell 編程
getPDF.aspx
getPDF.aspx
[圣思园][Java SE]Io 3
Clojure简介与应用
Study4.TW .NET Conf 2018 - Fp in c#
The Evolution of Async Programming (GZ TechParty C#)
Python 脚本入门基础
Python入門:5大概念初心者必備 2021/11/18
Ad

More from modou li (12)

PPTX
04.uliweb更多话题介绍
PPTX
03.uliweb开发进阶
PPTX
01.uliweb介绍
PPTX
02.uliweb开发入门
PPTX
03.python工作环境
PPTX
01.python介绍
PPT
Uliweb比较与实践 2013
PPTX
Python面向对象开发基础篇
PPTX
Uliweb设计分享
PDF
Uliweb cheat sheet_0.1
PDF
Uliweb框架思想与编程
PPT
Uliweb 快速易用的Python Web Framework
04.uliweb更多话题介绍
03.uliweb开发进阶
01.uliweb介绍
02.uliweb开发入门
03.python工作环境
01.python介绍
Uliweb比较与实践 2013
Python面向对象开发基础篇
Uliweb设计分享
Uliweb cheat sheet_0.1
Uliweb框架思想与编程
Uliweb 快速易用的Python Web Framework

02.python基础