一、Python简介
Python 是一种解释型语言,在 Python 中,由于内存管理是由 Python 解释器负责的。
Python 提供了“安全合理”的退出机制,让程序员能掌控局面。一旦你的 Python 由于错误崩溃,解释程序就会转出一个“堆栈跟踪”,那里面有可用到的全部信息,包括你程序崩溃的原因以及是那段代码(文件名、行数、行数调用等等)出错了。这些错误被称为异常。如果在运行时发生这样的错误,Python 使你能够监控这些错误并进行处理。
Python 是用 C 写的,又由于 C 的可移植性,使得 Python 可以运行在任何带有 ANSI C 编译器的平台上。尽管有一些针对不同平台开发的特有模块,但是在任何一个平台上用 Python 开发的通用软件都可以稍事修改或者原封不动的在其他平台上运行。这种可移植性既适用于不同的架构,也适用于不同的操作系统。
Python 的面向对象的特性是与生俱来的。然而,Python 绝不想 Java 或 Ruby 仅仅是一门面向对象语言,事实上它融汇了多种编程风格。例如,它甚至借鉴了一些像 Lisp 和 Haskell 这样的函数语言的特性。
文件扩展名 Python 源文件通常用.py 扩展名。当源文件被解释器加载或者显式地进行字节码编译的时候会被编译成字节码。由于调用解释器的方式不同,源文件会被编译成带有.pyc 或.pyo 扩展名的文件。
1.python可以做什么?
- 日常任务,小工具,eg:备份mp3,系统管理员需要的脚本任务
- 做网站,eg:YouTube,国内的豆瓣,Google,Yahoo
- 网络游戏的后台
- 爬虫
2.python不可以做什么?
- 操作系统只能用C语言编写
- 手机应用,IOS用Object-C, Android用Java
- 3D游戏,最好用C,C++
3.各系统下的Python的开发环境:
Windows: http://www.python.org/ftp/python/2.7.9/python-2.7.9.msi
Linux: yum install python -y
Mac:自带python2.7(OS>10.8)
4.python编辑器
linux:vim,emacs,gedit
windows:不要用记事本,会在每个文件的开始加一个特殊字符0xefbbbf,
notepad++
sublime
atom
5. python解释器
cpython
ipython:基于cpython,交互方式有所增强
pypy: 对代码进行动态编译,JIT技术(just-in-time compiler,即时编译器),显著提高代码执行速度。
Jpython: java平台上的python解释器,将python代码编译成java字节码执行。
IronPython: 直接将python代码编译成.net的字节码
6.安装python
[root@localhost ~]# yum install python
[root@localhost ipython]# yum install *
[root@localhost ~]# python ##启动python
要访问 Python, 除非你已经将 Python 所在路径添加到系统搜索路径之中, 否则就必须输入 Python 的完整路径名才可以启动 Python。Python 一般安装在 /usr/bin 或/usr/local/bin子目录中。
7.安装ipython
#yum install *
openpgm-5.2.122-2.el7.x86_64.rpmpython-ipython-3.2.1-1.el7.noarch.rpmpython-ipython-console-3.2.1-1.el7.noarch.rpmpython-ipython-gui-3.2.1-1.el7.noarch.rpmpython-jsonschema-2.3.0-1.el7.noarch.rpmpython-mistune-0.5.1-1.el7.x86_64.rpmpython-path-5.2-1.el7.noarch.rpmpython-pip-7.1.0-1.el7.noarch.rpmpython-pygments-1.4-9.el7.noarch.rpmpython-simplegeneric-0.8-7.el7.noarch.rpmpython-zmq-14.3.1-1.el7.x86_64.rpmzeromq3-3.2.5-1.el7.x86_64.rpm
#ipython ##启动ipython
二、Python基础知识
1.Python输出
print: 注意:不加引号默认是变量 可以作运算:
In [2]: a=hello ##不加引号默认是变量 --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-7264d036727a> in <module>() ----> 1 a=hello
NameError: name 'hello' is not definedIn [3]: a="hello" ##定义字符串变量a
In [4]: print a hello
In [5]: print 100+100 ##做运算 200
In [6]:
print 语句,与字符串格式运算符(% )结合使用,可实现字符串替换功能
示例:
>>> print "%s is number %d!" % ("Python", 1)Python is number 1!
2.输入:raw_input()
下划线(_)在解释器中有特别的含义,表示最后一个表达式的值。
示例:
In [19]: 9-3Out[19]: 6
In [20]: _Out[20]: 6
练习1:输入两个数字,相加后输出:
#!/usr/bin/python
a = raw_input("input first number:")
b = raw_input("input second number:")
print int(a)+int(b)
3.Python脚本
1)Python 脚本使用扩展名 .py2)脚本启动行
#!/usr/bin/python ##!后面跟的路径是你python解释器的绝对路径
当你不能确定 Python 的具体路径或者 Python 的路径经常变化时(但不能挪到系统搜索路径之外), env 就非常有用。它会帮你在系统搜索路径中找到 python 解释器。
如果你的系统拥有 env, 你的启动行就可以改为下面这样:
!/usr/bin/env python
或者, 如果你的 env 位于 /bin 的话,
#!/bin/env python
3)当python脚本中有中文时,需要制定编码格式:
#coding:utf-8
#coding=utf-8
#encoding:utf-8
#encoding=utf-8
#-*-coding:utf-8-*-
4)执行python脚本
a.不管哪种 Unix 平台, Python 脚本都可以象下面这样,在命令行上通过解释器执行:$ python script.py
b.给python脚本一个执行权限,直接用绝对路径的方式执行
$ ./script.py ##当前工作路径在脚本所在路径时,可以这样执行
5).python IDE
安装pycharm:
a.安装包pycharm-community-4.0.1.tar.gz
b.解压缩
[root@localhost software]# tar zxf pycharm-community-4.0.1.tar.gz -C /mnt/c.进入解压后目录
[root@localhost bin]# cd /mnt/pycharm-community-4.0.1/bind.[root@localhost bin]# ./pycharm.sh
之后就进入图形窗口
4.注释和大部分脚本及 Unix-shell 语言一样,Python 也使用 # 符号标示注释,从 # 开始,直到一行结束的内容都是注释。
5.变量定义原则
首字母小写,见名知义,驼峰标示,数字不能作首字母
python变量名是大小写敏感的
Python 是动态类型语言, 也就是说不需要预先声明变量的类型。 变量的类型和值在赋值那一刻被初始化。
Python 不支持 C 语言中的自增 1 和自减 1 运算符, 这是因为 + 和 - 也是单目运算符,Python 会将 --n 解释为-(-n) 从而得到 n , 同样 ++n 的结果也是 n.
Python 也支持增量赋值,也就是运算符和等号合并在一起
注意:python中两个变量相同时,两个名字指向的同一个内存地址
练习2:
交互模式:计算一月和四月分别有多少分钟,使用变量daysPerMonth,hoursPerDay,minutesPerHour 写脚本:
#!/usr/bin/python
#coding=utf-8
daysPerMonth1=31
daysPerMonth2=30
hoursPerDay=24
minutesPerHour=60
print "1月有",daysPerMonth1*hoursPerDay*minutesPerHour,"分钟"
print "4月有",daysPerMonth2*hoursPerDay*minutesPerHour,"分钟"
6.数值类型
(1)整形int:
(2)长整形long:
定义一个long变量a=1L
In [14]: a=1L
In [15]: type(a)
Out[15]: long
从长远来看, 整型与长整型正在逐步统一为一种整数类型。从 Python2.3 开始,再也不会报整型溢出错误, 结果会自动的被转换为长整数。在未来版本的 Python 中, 两种整数类型将会无缝结合, 长整数后缀 “L”也会变得可有可无。
In [9]: a=5 In [10]: type (2) Out[10]: int
In [11]: print a/2 2 ##除数被除数都是整形时,结果为整形,当二者其一是浮点型,答案为浮点型 In [6]: a=1.4
In [7]: type (a) Out[7]: float
In [8]: print a/2 0.7
浮点型的另一种表示方法:科学计数法 In [12]: a=1.2e-3
In [13]: print a 0.0012
(4)复数:complex 定义一个复数: In [16]: a=2j-3 In [18]: type(a) Out[18]: complex
(5)布尔值:True,False
7.运算符和表达式:
逻辑运算符:not,or,and
算术运算符:+,-,*,/,%,**
关系运算符:>,<,>=,<=,!=,==
赋值运算符:=,+=,-=*=,/=,%=
练习3:四则表达式,用if语句实现 if判断语句后要加:表示缩进
#!/usr/bin/python
#coding=utf-8
num1 = raw_input("input first number:")
operator = raw_input("input operater:")
num2 = raw_input("input second number:")
if operator == "+":
print num1,operator,num2,"=",int(num1)+int(num2)
elif operator == "-":
print num1,operator,num2,"=",int(num1)-int(num2)
elif operator == "*":
print num1,operator,num2,"=",int(num1)*int(num2)
elif operator == "/":
print num1,operator,num2,"=",float(num1)/float(num2)
else : print "operator error!"
三、序列
1.字符串
定义:
1)str = “hello”
2)str = ‘hello’
3)str = """hello""" 或 str = '''hello''' ##不会改变引号内的格式
In [1]: str = "hello"
In [2]: print str helloIn [3]: str = 'hello'
In [4]: print str hello
In [5]: str = """hello ...: i ...: am ...: """
In [6]: print str hello i am
In [7]: str = '''hello ...: i ...: am ...: '''
In [8]: print str hello i am
索引:
In [38]: a[1]
Out[38]: 'b'
字符串连接:
In [39]: a[1]+a[4]
Out[39]: 'be'
切片:
In [40]: a[1:4]
Out[40]: 'bcd'
In [41]: a[1:4:2] Out[41]: 'bd'In [42]: a[-1:-4] Out[42]: ''
In [43]: a[-1:-4:-1] Out[43]: 'edc'
In [44]: a[-1:-4:-2] Out[44]: 'ec'
In [45]: a[:] Out[45]: 'abcde'
求字符串长度:
In [1]: a="oiuy"
In [2]: len(a)
Out[2]: 4
*字符串重复:
In [3]: print "wu"*20
wuwuwuwuwuwuwuwuwuwuwuwuwuwuwuwuwuwuwuwu
判断字符串是否在某个字符串内:
In [1]: a="oiuy"
In [4]: "ad" in a
Out[4]: False
In [5]: "oi" in a
Out[5]: True
练习4:输入一个字符,判断是否在字符串中
#!/usr/bin/env python
str1="ljsoioi"
a=raw_input("input a word:")
if a in str1:
#print str1," has ",a
print "%s has %s" %(str1,a) ##两个都可以
else:
#print str1," has not ",a
print "%s has not %s" %(str1,a)
字符串内容的比较:
In [1]: str1="2531424"
In [2]: max(str1) ##求字符串里的最大值
Out[2]: '5'
In [3]: min(str1) ##求字符串里的最小值
Out[3]: '1'
In [4]: str1="45"In [5]: str2="123"
In [6]: cmp(str1,str2) ##比较俩个字符串的大小,一位一位比
Out[6]: 1 ##4>5,所以是1
可以将列表和元组当成普通的“数组”,它能保存任意数量任意类型的 Python 对象。和数组一样,通过从 0 开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象。列表和元组有几处重要的区别。列表元素用中括号( [ ])包裹,元素的个数及元素的值可以改变。元组元素用小括号(( ))包裹,不可以更改(尽管他们的内容可以)。元组可以看成是只读的列表。通过切片运算( [ ] 和 [ : ] )可以得到子集,这一点与字符串的使用方法一样。
2.元组:元素不可变
定义:
In [7]: t=()
In [9]: type(t)
Out[9]: tuple
In [10]: t=(1) ##当括号内只放一个数字时,为int型
In [11]: type(t)
Out[11]: int
In [14]: t=(1,) ##当括号内除了数字还有非字母符号,就可以变成元组
In [15]: type(t)
Out[15]: tuple
In [16]: user1 = ("fentiao", 4, "male")In [17]: type(user1)
Out[17]: tuple
In [18]: user2 = ("yangjian", 40000, "male")In [19]: type (user2)
Out[19]: tuple
In [21]: user1[0]
Out[21]: 'fentiao'
In [22]: user2[0]
Out[22]: 'yangjian'
In [24]: user2[0:2]
Out[24]: ('yangjian', 40000)
元组也可以进行切片运算,得到的结果也是元组(不能被修改):>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple[:3]('robots', 77, 93)
元组的其他用法:
1)t.count:
In [29]: t = (2,2,55,7,53,3)
In [33]: t.count(2)
Out[33]: 2
2)t.index:
In [35]: t=(2,5,7,9,3,4,2,5)
In [36]: t.index(2) ##在元组t中找2第一次出现的索引
Out[36]: 0
In [37]: t.index(2,3) ##在元组t中从索引3往后找,第一次出现2的索引
Out[37]: 6
In [38]: t.index(2,3,6) ##在元组t中找从索引3到索引6第一次出现2的索引 ValueError: tuple.index(x): x not in tuple
元组的元素不可修改,而列表可以
In [39]: print t (2, 5, 7, 9, 3, 4, 2, 5)
In [40]: t[1]=3 T
TypeError: 'tuple' object does not support item assignment
3.列表:元素可变 定义一个列表:
In [42]: li = []
In [43]: type(li)
Out[43]: list
修改列表元素:
In [45]: print li
[1, 'hello', [1, 2]]
In [46]: li[2]="world" In [47]: print li
[1, 'hello', 'world']
添加列表元素到末尾:
1.list.append
In [49]: li.append([1,2,3])
In [50]: print li
[1, 'hello', 'world', [1, 2, 3]]
2.list.extend
In [51]: li.extend([1,2,3])
In [52]: print li
[1, 'hello', 'world', [1, 2, 3], 1, 2, 3]
插入列表元素到指定位置:
In [54]: li.insert(2,2)
In [55]: print li
[1, 'hello', 2, 'world', [1, 2, 3], 1, 2, 3]
删除列表中某个元素:
In [62]: print li
[1, 2, 'world', [1, 2, 3], 1, 2, 3]
In [63]: li.remove(3) In [64]: print li
[1, 2, 'world', [1, 2, 3], 1, 2]
删除列表中指定位置的元素:
In [110]: print li
[2, 1, [1, 2, 3], 1]
In [111]: li.remove(li[0]) In [112]: print li [1, [1, 2, 3], 1] 或
In [112]: print li [1, [1, 2, 3], 1]
In [113]: del(li[0])In [114]: print li [[1, 2, 3], 1]
对列表中的元素排序:
In [73]: print t (1, 5, 7, 4)
In [77]: t.sort() In [78]: print t [2, 2, 4, 5, 6]
统计某个元素的出现次数:
In [79]: li.count(1)
Out[79]: 2
In [80]: print li
[1, 2, 'world', [1, 2, 3], 1, 2]
找固定范围内某个值第一次出现的索引:
In [96]: li.index(1,1)
Out[96]: 2
查看并删除指定位置的值:
In [95]: print li [1, [1, 2, 3], 1, 2]
In [100]: li.pop(3) Out[100]: 2 In [101]: print li [1, [1, 2, 3], 1]
换为反序列:
In [108]: print li [1, [1, 2, 3], 1, 2]
In [109]: li.reverse()
In [110]: print li [2, 1, [1, 2, 3], 1]
4.集合:不重复,无序 求差集
1. s1-s2
In [115]: s1={1,2,3,4}
In [117]: s2={1,2,3}
In [119]: s1-s2
Out[119]: {4}
2.s1.difference(s2)
In [125]: s1.difference(s2)
Out[125]: {4}
In [126]: s1
Out[126]: {1, 2, 3, 4}
3.s1.difference_update(s2)
In [127]: s1.difference_update(s2)
In [128]: s1 Out[128]: {4}
求交集
1.s1&s2
In [130]: s1&s2
Out[130]: {1, 2, 3}
2.s1.intersection(s2)
In [132]: s1.intersection(s2)
Out[132]: {1, 2, 3}
3.s1.intersection_update(s2)
In [133]: s1.intersection_update(s2)
In [134]: s1
Out[134]: {1, 2, 3}
求并集
In [137]: s1.union(s2)
Out[137]: {1, 2, 3, 4}
将列表变为集合:
In [142]: li=[1,2,3,4]
In [143]: set(li)
Out[143]: {1, 2, 3, 4}
添加列表到集合里:
In [146]: s1.add([1,2,3,4])
---------------------------------------------------------------------------
TypeError
Traceback (most recent call last)
<ipython-input-146-595152cc9699> in <module>() ----> 1 s1.add([1,2,3,4])
In [147]: s1.update([5,6,7])
In [148]: s1
Out[148]: {1, 2, 3, 4, 5, 6, 7, 45}
删除集合里的指定元素:
1.remove
In [149]: s1.remove(1)
In [150]: s1
Out[150]: {2, 3, 4, 5, 6, 7, 45}
In [151]: s1.remove(9)
2.discard
In [152]: s1.discard(9)
In [153]: s1 Out[153]: {2, 3, 4, 5, 6, 7, 45}In [154]: s1.discard(7)
In [155]: s1 Out[155]: {2, 3, 4, 5, 6, 45}
3.pop
In [160]: s1.pop() Out[160]: 4
4.clear ##删除所有元素 判断是否不是子集:
In [162]: s1.isdisjoint(s2) Out[162]: True
In [163]: s2 Out[163]: {1, 2, 3} In [164]: s1 Out[164]: {5, 6, 45}
判断是否是子集:
In [166]: s1={1,2}
In [168]: s1.issubset(s2)
Out[168]: True
In [169]: s1={1,2,3}In [170]: s1.issubset(s2) Out[170]: True 判断是否是父集: In [172]: s1={1,2,3,4,5}
In [173]: s1.issuperset(s2) Out[173]: True In [174]: s1={1,2}
In [175]: s1.issuperset(s2) Out[175]: False
字符串,元组,列表,集合之间的相互转化
In [9]: tuple("str") ##字符串变元组Out[9]: ('s', 't', 'r')
In [8]: tuple({1,2,3}) ##集合变元组Out[8]: (1, 2, 3)
In [7]: tuple([1,2,3]) ##列表变元组Out[7]: (1, 2, 3)
In [6]: set([1,2,4,5]) ##列表变集合Out[6]: {1, 2, 4, 5}
In [11]: set("str") ##字符串变集合Out[11]: {'r', 's', 't'}
In [12]: set((1,2,3,4)) ##元组变集合Out[12]: {1, 2, 3, 4}
In [1]: list("str") ##字符串变列表Out[1]: ['s', 't', 'r']
In [2]: list((2,3,4,5)) ##元组变列表Out[2]: [2, 3, 4, 5]
In [4]: list({2,3,4,5}) ##集合变列表Out[4]: [2, 3, 4, 5]
5.字典
1)定义:
In [18]: dic = {"name":"lee","age":"30","gender":"male"}
2)查看:
In [20]: dic.values() ##显示字典的值
Out[20]: ['male', '30', 'lee']
In [21]: dic.keys() ##显示字典的键
Out[21]: ['gender', 'age', 'name']
In [22]: dic.items() ##显示字典的键值对
Out[22]: [('gender', 'male'), ('age', '30'), ('name', 'lee')]
In [59]: dic.viewitems() ##显示键值对
Out[59]: dict_items([('status', 'happy'), ('gender', 'male'), ('age', '30'), ('name', 'hello')])
In [61]: dic.viewkeys() ##显示键
Out[61]: dict_keys(['status', 'gender', 'age', 'name'])
In [62]: dic.viewvalues() ##显示值
Out[62]: dict_values(['happy', 'male', '30', 'hello'])
In [23]: for k,v in dic.items(): ##循环输出键值对
In [42]: dic["name"] ##显示某个键对应的值
Out[42]: 'lee' In [40]: dic.get("name") ##显示某个键对应的值
Out[40]: 'lee' In [45]: dic.has_key("name") ##判断某个键是否存在
Out[45]: True 3)添加:
a: In [50]: dic.update({"name":"wu"})##更新name为wu,name不存在时添加
In [51]: dic Out[51]: {'age': '30', 'gender': 'male', 'name': 'wu'}
b:
In [52]: dic["name"]="hello" ##更新name为hello,name不存在时添加
In [53]: dic Out[53]: {'age': '30', 'gender': 'male', 'name': 'hello'}
c:
In [54]: dic.setdefault("name","liu") ##设置name为liu,但是因为name有值,所以不更新,这是他与前两个的区别 Out[54]: 'hello'
In [55]: dic Out[55]: {'age': '30', 'gender': 'male', 'name': 'hello'}
In [56]: dic.setdefault("status","happy") ##当status不存在时添加 Out[56]: 'happy'
In [57]: dic Out[57]: {'age': '30', 'gender': 'male', 'name': 'hello', 'status': 'happy'} 4)删除: a.删除字典中的某一项
a1:
In [69]: del dic["oiuo"] ##删除oiuo
In [70]: dic Out[70]: {'age': '30', 'gender': 'male', 'kind': 'll', 'name': 'hello', 'status': 'happy'}
a2:
In [71]: dic.pop("kind") ##删除kind Out[71]: 'll'
In [72]: dic Out[72]: {'age': '30', 'gender': 'male', 'name': 'hello', 'status': 'happy'}
b:删除字典中的所有内容
In [73]: dic.clear() ##清空dic
In [74]: dic Out[74]: {}c:删除字典
In [75]: del dic ##删除dic
In [30]: it=dic.iterkeys() ##返回键的迭代器
In [31]: it=dic.itervalues() ##返回值的迭代器
In [32]: it=dic.iteritems() ##返回键值对的迭代器
In [79]: dic1=dic.copy() ##dic复制一份给dic1In [80]: dic2=dic ##dic复制一根给dic2
In [81]: id(dic) Out[81]: 37656864
In [82]: id(dic1) ##dic1与dic的地址不一致,复制的是内容
Out[82]: 37635664
In [83]: id(dic2) ##dic2与dic的地址一致,复制的是地址
Out[83]: 37656864
In [90]: dic1=dic.fromkeys(["a","b","c"]) In [91]: dic1 Out[91]: {'a': None, 'b': None, 'c': None}
In [92]: dic1=dic.fromkeys(["a","b","c"],"wu")
In [93]: dic1 Out[93]: {'a': 'wu', 'b': 'wu', 'c': 'wu'}
特殊用法:
for name,pwd in dic.items():
for i in dic.keys():
time.ctime(time.time()) ##将秒变成时间
三、函数
默认参数放后面,变化性大的放后面,变化性小的放前面
In [3]: def info(name,age=2,address="xian"):
...: print name,age,address
...:
In [4]: info('sdf')
sdf 2 xian
In [5]: def info(age=2,name,address="xian"):
...: print name,age,address
...:
File "<ipython-input-5-9e77bc1100a6>", line 1
def info(age=2,name,address="xian"):
SyntaxError: non-default argument follows default argument
默认参数必须是不可变的
可变参数;
#!/usr/bin/env python
def add(*args):
sum=0
print type(args)
for i in args:
sum=sum+i
return sum
print add(1,2,3,4,5)
L = [1,2,3]
print add((*L)
函数 vs 过程
我们经常拿函数和过程比较。两者都是可以被调用的实体,但是传统意义上的函数或者“黑盒”,
可能不带任何输入参数,经过一定的处理,最后向调用者传回返回值。其中一些函数则是布尔类型
的, 返回一个“是“或者“否“的回答,更确切地说,一个非零或者零值。而过程是简单,特殊,
没有返回值的函数。从后面内容你会看到,python 的过程就是函数,因为解释器会隐式地返回默认
值 None
从返回值的角度来考虑, 可以通过很多方式来存储元组。接下来的 3 种保存返回值的方式是等
价的
>>> aTuple = bar()
>>> x, y, z = bar()
>>> (a, b, c) = bar()
在对 x,y,z 和 a,b,c 的赋值中,根据值返回的顺序, 每个变量会接收到与之对应的返回值。而
aTuple 直接获得函数隐式返回的整个元组。回想一下,元组既可以被分解成为单独的变量,也可以直
接用单一变量对其进行引用。
time.ctime(time.time()) ##将秒变成时间