导图社区 Python入门教程编程基础知识框架笔记思维导图
Python入门教程编程基础知识框架笔记思维导图,一张图带你完全了解相关内容,帮你提高效率,赶紧来试一试吧~
编辑于2023-02-22 23:27:43 广东Python入门教程编程基础知识框架笔记思维导图
数据类型
基本类型
整数int
表示方法
a=1234
十六进制a=0xff
八进制a=025
二进制a=0b11
In [73]: 0xff Out[73]: 255 In [74]: 0b11 Out[74]: 3 In [75]: 010 Out[75]: 8
操作
转化为浮点数float
In [64]: float(23) Out[64]: 23.0
转化为字符串str
In [65]: str(9) Out[65]: '9'
转化为二进制bin
In [76]: bin(3) Out[76]: '0b11'
转化为十六进制hex
In [68]: hex(13) Out[68]: '0xd'
转化为八进制oct
In [67]: oct(8) Out[67]: '010'
绝对值abs
In [77]: abs(-9) Out[77]: 9
浮点数float
表示方法
a=1.234
操作
舍入round
In [61]: round(3.4) Out[61]: 3.0 In [62]: round(3.5) Out[62]: 4.0
取整int
In [63]: int(9.6) Out[63]: 9
字符串string
表示方法
s='abcdefg'
s="abcdefg"
s="""abcdefg"""
s='''abcdefg'''
转义
转义符\
操作
查找find
In [78]: 'what a day'.find('a') Out[78]: 2 In [79]: 'what a day'.find('da') Out[79]: 7
右端查找rfind
In [80]: 'what a day'.rfind('da') Out[80]: 7 In [81]: 'what a day'.rfind('a') Out[81]: 8 从右端开始查找,返回第一个遇到的结果
分割split
In [82]: 'what a day'.split('a') Out[82]: ['wh', 't ', ' d', 'y'] In [83]: 'what a day'.split(' ') Out[83]: ['what', 'a', 'day']
替换replace
In [85]: 'what a day'.replace('a','X') Out[85]: 'whXt X dXy' In [86]: 'what a day'.replace('what','how') Out[86]: 'how a day'
大写upper小写lower
In [88]: s='hello' In [89]: s.upper() Out[89]: 'HELLO' In [90]: 'Kate'.lower() Out[90]: 'kate'
计数count
In [91]: 'what a day'.count('a') Out[91]: 3
长度len
字符串的长度len(str) In [9]: len('abcd') Out[9]: 4
检查是否是数字isdigit
In [94]: '123'.isdigit() Out[94]: True
合并join
In [95]: ','.join(['what','a','day']) Out[95]: 'what,a,day' In [96]: ' '.join(['what','a','day']) Out[96]: 'what a day'
查看开头是否以某个片段开始startswith
In [6]: s Out[6]: 'asasdfew' In [7]: s.startswith('as') Out[7]: True
查看结尾是否以某个片段结束endswith
In [9]: s Out[9]: 'asasdfew' In [10]: s.endswith('as') Out[10]: False
chr/ord
ord将字符转化为相应的ascii序号
chr将数字转化为相应的ascii字符
In [56]: ord('a') Out[56]: 97 In [57]: chr(98) Out[57]: 'b'
正则
正则是一种处理数据的方式。是一种通过一定的模式来匹配到目标的方法。 可以用于查找文本中的固定模式的字符串。
模块:re
例如查找文本中的物品价格 In [94]: r=re.compile(r'price.*(:|is )(\$?[0-9]+)') #这个表达式可以匹配很多模式的价格写法 In [95]: r.findall('the price is 55') Out[95]: [('is ', '55')] In [96]: r.findall('the price is $55') Out[96]: [('is ', '$55')] In [97]: r.findall('the price:$55') Out[97]: [(':', '$55')] In [98]: r.findall('the price of apple is:$55') Out[98]: [(':', '$55')] In [99]: r.findall('the price of apple is $55') Out[99]: [('is ', '$55')] In [100]: r.findall('the price of apple:$55') Out[100]: [(':', '$55')]
定制(格式化)字符串
旧方式,使用%
定制字符串 In [4]: n Out[4]: 'Jone Doe' In [5]: 'His name is %s'%n Out[5]: 'His name is Jone Doe'
定制数字 In [6]: a,b=1,2 In [7]: '%d + %d = %d'%(a,b,a+b) Out[7]: '1 + 2 = 3' In [13]: 'time: %02d:%02d:%d'%(2,3,56) Out[13]: 'time: 02:03:56'
定制浮点数 In [22]: 'Money is:%2.3f'%5.3 Out[22]: 'Money is:5.300'
新方式,使用format函数。更灵活更强大
字符串 In [42]: '{0} is {1} years old. '.format('Mon', 4) Out[42]: 'Mon is 4 years old. ' 补齐长度 In [60]: '{0:8} is a 8 length. '.format('Kath') Out[60]: 'Kath is a 8 length. ' 数字精度 In [72]: "Pi is {0:.3}".format(3.1415926) Out[72]: 'Pi is 3.14' 别名替换 In [62]: '{first} is as {second}. '.format(first='Caro', second='Wendy') Out[62]: 'Caro is as Wendy. ' 调用属性 In [66]: 'E is {0.e}'.format(math) Out[66]: 'E is 2.71828182846'
更多组合例子 In [90]: import math In [91]: '{0.e:06.3} {0.pi:08.4}'.format(math) Out[91]: '002.72 0003.142' 居右填充 In [101]: '{0.e:06.3} {0.pi:_>8.4}'.format(math) Out[101]: '002.72 ___3.142' 居左填充 In [102]: '{0.e:06.3} {0.pi:_<8.4}'.format(math) Out[102]: '002.72 3.142___' 居中填充 In [103]: '{0.e:06.3} {0.pi:_^9.4}'.format(math) Out[103]: '002.72 __3.142__' 整数格式化为不同进制的数 二进制 In [134]: '{0:b}'.format(8) Out[134]: '1000' 八进制 In [135]: '{0:o}'.format(8) Out[135]: '10' 十六进制 In [137]: '{0:x}'.format(18) Out[137]: '12' 用,做千位分隔符。 In [47]: '{:,}'.format(1234567890) Out[47]: '1,234,567,890' 嵌套使用 In [149]: '{0:_^{1}}'.format(12347,10) Out[149]: '__12347___' In [150]: '{0:_^{1}}'.format(12347,20) Out[150]: '_______12347________'
真值Boolean
表示方法
真True(值等于1)
假Fasle(值等于0)
无None
表示方法
None
其他
复数
表示方法
a=1+2j
操作
In [151]: a=1+2j 实部 In [152]: a.real Out[152]: 1.0 虚部 In [153]: a.imag Out[153]: 2.0 共轭复数 In [155]: a.conjugate() Out[155]: (1-2j)
字节类型bytes
与字符串类似。是字符串的二进制形式。
字节向量bytearray
表示方法
一个长度为10的字节向量 In [16]: a=bytearray(10) In [17]: a Out[17]: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') In [18]: a[9]=1 In [19]: a Out[19]: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01')
分片、赋值、循环等操作均与列表类似
结构化数据
列表list
表示方法
a=[1,2,4]
a=[1.2,3,6]
['a','asd','df']
['1,'as',[1,2,3]]
a=None b=[1,2,3,a]
多维
二维a=[[1,2],[3,4]]
三维a=[[[1,2],[3,4]],[[5,6],[7,8]]]
操作
前提条件: In [156]: a=range(10) In [157]: a Out[157]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
分片[]
取单个元素 In [158]: a[3] Out[158]: 3 索引值从0开始 In [159]: a[0] Out[159]: 0 取中间一部分,不包括尾部的索引数 In [160]: a[2:5] Out[160]: [2, 3, 4] 省略前面的索引值 In [161]: a[:5] Out[161]: [0, 1, 2, 3, 4] 省略后面的索引值 In [162]: a[6:] Out[162]: [6, 7, 8, 9] 取出末尾的元素 In [176]: a[-1] Out[176]: 9 取出后两个 In [177]: a[-2:] Out[177]: [8, 9] 取出全部 In [163]: a[:] Out[163]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 逆序取出 In [166]: a[::-1] Out[166]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 逆序取出索引值3后面的 In [167]: a[:3:-1] Out[167]: [9, 8, 7, 6, 5, 4] 逆序取出索引值3前面的 In [170]: a[3::-1] Out[170]: [3, 2, 1, 0] 间隔3取出 In [175]: a[::3] Out[175]: [0, 3, 6, 9]
多维操作,相当于对取出的分片再次分片。
使用运算符
In [207]: [1,2]+[3,4] Out[207]: [1, 2, 3, 4] In [208]: [2,3]*4 Out[208]: [2, 3, 2, 3, 2, 3, 2, 3]
比较运算按照元素依次比较 In [213]: [2,8]>[5,0] Out[213]: False In [214]: [2,8]>[1,5] Out[214]: True In [218]: [2,3,4]<[2,3,5] Out[218]: True In [220]: [2,3,4]==[2,3,4] Out[220]: True
末尾添加元素append
In [180]: a.append(3) In [181]: a Out[181]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
元素计数count
In [181]: a Out[181]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3] In [182]: a.count(3) Out[182]: 2
长度len
In [8]: len([1,2,3,4]) Out[8]: 4
插入insert
插入指定位置,元素 In [183]: a.insert(0,42) In [184]: a Out[184]: [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
扩展extend
In [185]: a.extend([55,66,77]) In [186]: a Out[186]: [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 55, 66, 77]
元素索引值index
In [186]: a Out[186]: [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 55, 66, 77] In [187]: a.index(55) Out[187]: 12 In [188]: a[12] Out[188]: 55
弹出元素pop
In [186]: a Out[186]: [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 55, 66, 77] 去除尾部的元素,并返回该值 In [189]: a.pop() Out[189]: 77 In [190]: a Out[190]: [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 55, 66] 去除索引值的元素,并返回该值 In [191]: a.pop(0) Out[191]: 42 In [192]: a Out[192]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 55, 66]
移除元素remove
移除第一个指定元素 In [193]: a.remove(55) In [194]: a Out[194]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 66]
排序sort
In [197]: s=[23,4,5,765,75,3] 排序,在原列表上操作 In [198]: s.sort() In [199]: s Out[199]: [3, 4, 5, 23, 75, 765] 逆序排序 In [201]: s.sort(reverse=True) In [202]: s Out[202]: [765, 75, 23, 5, 4, 3]
逆序reverse
In [203]: a Out[203]: [0, 1, 2, 4, 5, 6, 7, 8, 9, 3, 66] 将列表的元素倒转 In [204]: a.reverse() In [205]: a Out[205]: [66, 3, 9, 8, 7, 6, 5, 4, 2, 1, 0]
map函数
map函数是一种以函数为参数的函数。使用为: map(操作函数,序列) 执行中会对每一个应用操作函数。map函数代表了一类函数, 这些函数通常都使用函数做参数,并对每个元素进行操作。
对列表中的每一个元素求绝对值 [101]: map(abs,[1,2,-4,-22,5]) Out[101]: [1, 2, 4, 22, 5] 求0-9的平方,使用了lambda函数 In [102]: map(lambda x:x**2,range(10)) Out[102]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
循环和列表表达式
循环
for i in list: __somthing__
列表表达式
列表表达式提供和循环/map函数类似的功能,但书写更简洁。 其功能较map灵活,较循环简单。运行速度比map稍微快一点。
In [42]: [i**3 for i in range(5)] Out[42]: [0, 1, 8, 27, 64] In [43]: [i**3 for i in range(9) if i%2==0] Out[43]: [0, 8, 64, 216, 512] In [46]: [i*j for i in range(1,3) for j in range(1,5)] Out[46]: [1, 2, 3, 4, 2, 4, 6, 8]
元组tuple
表示方法
a=(1,2,4)
a=(1.2,3,6)
('a','asd','df')
('1,'as',(1,2,3))
a=None b=(1,2,3,a)
操作
分片
index
count
长度
使用运算符
字典dict
表示方法
d={'a':123,'b':456}
d={12:'asd', 33:[1,2,3], (2,4):'ffff'}
操作
基本操作
In [242]: d={'name':'Kim','age':22} In [243]: d Out[243]: {'age': 22, 'name': 'Kim'} 调用键值 In [244]: d['age'] Out[244]: 22 新增键值对 In [245]: d['phone']=5223528 In [246]: d Out[246]: {'age': 22, 'name': 'Kim', 'phone': 5223528}
所有的键keys、值values、元素items
键 In [247]: d.keys() Out[247]: ['phone', 'age', 'name'] 值 In [248]: d.values() Out[248]: [5223528, 22, 'Kim'] 键值对 In [249]: d.items() Out[249]: [('phone', 5223528), ('age', 22), ('name', 'Kim')]
相应的迭代器为iteritems iterkeys itervalues,迭代器更加节省内存资源。
剔除元素(按照键)pop
In [252]: d.pop('age') Out[252]: 22 In [253]: d Out[253]: {'name': 'Kim', 'phone': 5223528}
剔除元素popitem
In [265]: d={'name':'Kim','age':22,'other':None} In [266]: d.popitem() Out[266]: ('age', 22) In [267]: d Out[267]: {'name': 'Kim', 'other': None}
获取/添加值setdefault
In [277]: d={'name':'Kim','age':22,'other':None} In [278]: d.setdefault('about') #如键不存在,添加默认值为None In [279]: d Out[279]: {'about': None, 'age': 22, 'name': 'Kim', 'other': None} #如存在,返回其值 In [280]: d.setdefault('name') Out[280]: 'Kim'
是否存在键名has_key
In [281]: d.has_key('age') Out[281]: True
获取值get
In [282]: d.get('small',20) Out[282]: 20 #如所要获取的键不存在,返回括号里的第二个参数的值 In [283]: d.get('age',20) Out[283]: 22 #如获取的键存在,返回字典中的值
从一个序列中生成一个字典fromkeys
In [292]: d.fromkeys(['age','fond of'],None) Out[292]: {'age': None, 'fond of': None} 第二个参数是默认值
使用另一个字典更新update
In [294]: d Out[294]: {'about': None, 'age': 22, 'name': 'Kim', 'other': None} In [295]: s={'dog':'Harry','cat':'miao'} In [296]: d.update(s) In [297]: d Out[297]: {'about': None, 'age': 22, 'cat': 'miao', 'dog': 'Harry', 'name': 'Kim', 'other': None}
清空字典clear
In [314]: d.clear() In [315]: d Out[315]: {}
集合set
表示方法
d={1,2,3,4,5}
d={'a','b',456,4.5}
操作
基本
In [312]: s={1,2,3,4,1,2,3,5} In [313]: s Out[313]: set([1, 2, 3, 4, 5]) 集合中不允许重复元素存在
添加元素add
In [342]: s Out[342]: set([1, 2, 3]) In [343]: s.add(9) In [344]: s Out[344]: set([1, 2, 3, 9])
删除元素discard
In [374]: s Out[374]: set([1, 2, 3, 5, 6, 7, 9]) In [375]: s.discard(5) In [376]: s Out[376]: set([1, 2, 3, 6, 7, 9]) In [377]: s.discard(55) #不存在的元素将不操作 In [378]: s Out[378]: set([1, 2, 3, 6, 7, 9])
使用一个集合(或序列)更新update
In [371]: s Out[371]: set([1, 2, 3, 9]) In [372]: s.update([1,2,5,6,7]) In [373]: s Out[373]: set([1, 2, 3, 5, 6, 7, 9])
交集并集差集
In [350]: s1 Out[350]: set([-1, 1, 4, 5, 8]) In [351]: s2 Out[351]: set([3, 4, 5, 6, 7, 8]) 交集,s1和s2共有的元素: In [352]: s1 & s2 Out[352]: set([4, 5, 8]) 并集,s1或s2存在的元素: In [353]: s1 | s2 Out[353]: set([-1, 1, 3, 4, 5, 6, 7, 8]) 对称差集,s1或s2中存在,但不同时存在两者中的元素: In [354]: s1 ^ s2 Out[354]: set([-1, 1, 3, 6, 7]) 差集,只在s1中存在但不在s2中存在的元素: In [355]: s1-s2 Out[355]: set([-1, 1])
并集union,相当于|
In [360]: s Out[360]: set([1, 2, 3, 9]) In [361]: s.union([5,56]) Out[361]: set([1, 2, 3, 5, 9, 56])
差集difference,相当于-
In [363]: s1 Out[363]: set([-1, 1, 4, 5, 8]) In [364]: s2 Out[364]: set([3, 4, 5, 6, 7, 8]) In [365]: s1.difference(s2) Out[365]: set([-1, 1])
交集intersection,相当于&
In [366]: s1.intersection(s2) Out[366]: set([4, 5, 8])
对称差集symmetric_difference,相当于^
In [368]: s1.symmetric_difference(s2) Out[368]: set([-1, 1, 3, 6, 7])
各种集合有对应的xxx_update更新函数
比较<>==
>、<表示一个集合是否是另一个集合的子集
In [5]: s1={1,2} In [6]: s2={1,2,3} In [7]: s1>s2 Out[7]: False s1是s2的子集 In [8]: s1<s2 Out[8]: True In [9]: s2={6,2,3} In [10]: s1>s2 Out[10]: False s1和s2没有包含关系 In [11]: s1<s2 Out[11]: False
序列
序列是对一类数据结构的统称,他们通常有一些类似的操作:
操作
元素总数len
适用于:所以 其中字典表示的是键值对的个数
分片操作
适用于:除字典、集合外的其他序列 其中字典可以使用 [键名] 获取键的属性
for循环、迭代
适用于:所有
字典可以用 for k in dict:遍历键 for k,v in dict.items():遍历键值对
比较操作>,<,==,!=
适用于:所有
单行表达式
适用于:所有
对于所有可以循环的序列类型的数据, 都可以用于单行表达式。单行表达式 比循环更加优雅。
列表操作 In [49]: [i*2 for i in range(5)] Out[49]: [0, 2, 4, 6, 8]
生成集合 In [47]: {i for i in [1,2,12,3,1,2,3,4]} Out[47]: set([1, 2, 3, 4, 12])
生成字典 In [48]: {k:v for k,v in [('a',1),('b',2)]} Out[48]: {'a': 1, 'b': 2}
圆括得到的不是元组,而是生成器 In [50]: (i for i in range(10) if i%3==0) Out[50]: <generator object <genexpr> at 0x024AE508> In [51]: a=(i for i in range(10) if i%3==0) In [52]: for i in a: ....: print i, ....: 0 3 6 9
操作字符串 In [55]: [ord(i) for i in 'abcd'] Out[55]: [97, 98, 99, 100]
map类型函数
map
map(fun,seq1,seq2,...) 其中fun为一个参数个数 与序列个数相对应的函数。
reduce
In [21]: reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) Out[21]: 15
递归式地操作序列中的数据,相当于((((1+2)+3)+4)+5)
filter
In [23]: filter(lambda x:x%2==0, [1, 2, 3, 4, 5]) Out[23]: [2, 4]
以一定的规则过滤元素,其中fun函数返回真值True/False
序列函数
sorted排序
适用于:所有
In [30]: s=[2,1,4,5,3] In [31]: sorted(s) Out[31]: [1, 2, 3, 4, 5] In [32]: s=[(1,2),(-4,8),(7,0)] In [33]: sorted(s) Out[33]: [(-4, 8), (1, 2), (7, 0)] key参数指定比较对象 In [34]: sorted(s,key=lambda x:x[1]) Out[34]: [(7, 0), (1, 2), (-4, 8)]
max/min
最大值/最小值
In [37]: s=[(1,2),(-4,8),(7,0)] 默认比较方式 In [38]: max(s),min(s) Out[38]: ((7, 0), (-4, 8)) 指定比较对象 In [39]: max(s,key=lambda x:x[1]) Out[39]: (-4, 8)
all/any
all/any(序列) 一个序列是否所有/任意值为真
sum
数值序列求和
zip
zip(seq1,seq2) 压缩两个序列,使之变为一个
In [58]: zip([1,2,3],['a','b','c']) Out[58]: [(1, 'a'), (2, 'b'), (3, 'c')]
其他结构
栈
堆
队列
有初始值的字典
有序字典
运算操作
算术运算
加+
1+2
a+b
a+3
减/负号-
a=-1
-a
3-a
乘*
5*8
除/
2.x版本
In [379]: 3/2 Out[379]: 1 In [380]: 3/2.0 Out[380]: 1.5
3.x版本
In [3]: 3/2 Out[3]: 1.5
乘方**
In [381]: 2**32 Out[381]: 4294967296L
取余%
In [382]: 10%3 Out[382]: 1 In [383]: 2%3 Out[383]: 2
关系运算
大于>、小于<
a<4
2<3
In [394]: 3<5<8 Out[394]: True In [395]: 3<5<2 Out[395]: False
In [398]: (3,5)<(4,4) Out[398]: True 对序列比较,按照元素依次比较
大于等于>=、小于等于<=,同上
等于==、不等于!=
In [396]: 3==3!=4 Out[396]: True In [397]: 3!=3!=4 Out[397]: False
逻辑运算
非
not (A)
In [46]: not 0 , not 1 Out[46]: (True, False) In [47]: not True , not False Out[47]: (False, True)
与
(A) and (B)
In [49]: 1 and 5 Out[49]: 5 In [50]: True and 0 Out[50]: 0 In [51]: True and False Out[51]: False In [52]: False and 5 Out[52]: False
或
(A) or (B)
In [55]: 3 or 5 Out[55]: 3 In [56]: False or 5 Out[56]: 5 In [57]: False or True Out[57]: True
位运算符
取反
~A
In [19]: ~5 Out[19]: -6 In [20]: bin(5),bin(-6) Out[20]: ('0b101', '-0b110')
与
A&B
In [24]: 3&2 Out[24]: 2 In [25]: 3&4 Out[25]: 0 In [26]: bin(3),bin(2) Out[26]: ('0b11', '0b10') In [27]: bin(3),bin(4) Out[27]: ('0b11', '0b100')
或
A|B
In [28]: 3|4 Out[28]: 7 In [29]: bin(3),bin(4),bin(7) Out[29]: ('0b11', '0b100', '0b111')
异或
A^B
In [36]: 3^6 Out[36]: 5 In [37]: bin(3),bin(6),bin(5) Out[37]: ('0b11', '0b110', '0b101')
移位(按二进制位移动)
左移<<
In [13]: 16>>2 Out[13]: 4
右移>>
In [16]: 1<<6 Out[16]: 64
赋值运算符
直接赋值=
In [384]: a=b=c=2 In [385]: a,b,c Out[385]: 2,2,2
In [388]: a,b=2,3 In [389]: a,b Out[389]: 2,3
In [389]: a,b Out[389]: 2,3 In [391]: a,b=b,a In [392]: a,b Out[392]: 3,2
自增赋值+=
In [33]: a=3 In [34]: a+=4 In [35]: a Out[35]: 7
自减赋值-=,同上
其他自增赋值,同上
*=
/=
%=
**=
&=
|=
^=
控制结构
顺序
按顺序按行依次书写代码,无特殊要求。 每行是一个语句。语句也可以使用;分割。
例如交换两个变量 In [400]: a=2;b=3 In [401]: t=a In [402]: a=b In [403]: b=t In [404]: a,b Out[404]: (3, 2)
选择(分支)
if
如果条件成立就执行,其他的情况不考虑。格式如下: if __条件表达式__ : __语句__ #注意前面的空格是必须的,称为缩进 __语句__ #空格的长度要和前面的一致 __if外的语句__ #当缩进回到上一级,自动退出当前if结构
In [1]: if 3>5: ...: print '3 is bigger' ...: 条件不成立时,冒号后面的将不执行 In [2]: if 5>3: ...: print '5 is bigger' ...: 5 is bigger
if else
如果条件成立就执行,其他的情况则执行else下的语句。格式如下: if __条件表达式__ : __语句__ #注意前面的空格是必须的,称为缩进 __语句__ #空格的长度要和前面的一致 else: __语句__ #注意前面的空格是必须的,称为缩进 __语句__ #空格的长度要和前面的一致 __if外的语句__ #当缩进回到上一级,自动退出当前if-else结构
In [3]: if 3>5: ...: print '3 is bigger' ...: else: ...: print '5 is bigger' ...: 5 is bigger
if elif ... else
如果条件成立n成立就执行下面的语句,其他的情况则执行else下的语句(else语句可省略)。格式如下: if __条件表达式1__ : __语句__ #注意前面的空格是必须的,称为缩进 __语句__ #空格的长度要和前面的一致 elif __条件表达式2__: __语句__ #空格的长度要和前面的一致 elif __条件表达式3__: __语句__ #空格的长度要和前面的一致 ...... else: __语句__ #空格的长度要和前面的一致 __if外的语句__ #当缩进回到上一级,自动退出当前if-else结构
情形1 In [4]: a=8 In [5]: if a>10: ...: print 'a is bigger than 10' ...: elif a<0: ...: print 'a is negative' ...: else: ...: print 'a is in [0,10]' ...: a is in [0,10] 情形2 In [6]: a=-5 In [7]: if a>10: ...: print 'a is bigger than 10' ...: elif a<0: ...: print 'a is negative' ...: else: ...: print 'a is in [0,10]' ...: a is negative
单行if else
写法: __值1__ if __真值表达式__ else __值2__ 表达式为真时结果为值1,反之为值2
情形1 In [37]: k=2 In [38]: a= -1 if k%2==0 else 1 In [39]: a Out[39]: -1 情形2 In [40]: k=3 In [41]: a= -1 if k%2==0 else 1 In [42]: a Out[42]: 1
循环(重复)
for
写法: for __循环变量名__ in __序列__: __语句__ #注意前面的缩进 __循环外语句__ #减少缩进量退出循环
In [43]: for i in [1,2,3,4]: ....: print i**2, ....: 1,4,9,16 嵌套使用 In [44]: for i in range(5): ....: if i%2==0: ....: print i,'is even' ....: else: ....: print i,'is odd' ....: 0 is even 1 is odd 2 is even 3 is odd 4 is even
while
写法: while __真值表达式__: __语句__ #注意前面的缩进 __循环外语句__ #减少缩进量退出循环
i=0 In [3]: while i<8: ...: print i**2, ...: i+=1 ...: 0 1 4 9 16 25 36 49
pass、break、continue语句
pass不执行
break中断循环
continue跳过后面的代码,继续下一个循环
流程图
一种帮助理解、构建程序的方法。 由框图,和带箭头的线条构成。 用来表示顺序、选择、循环结构 的组合运用
函数和对象
函数
函数是一种具有某种功能的代码块。 通常可以达到代码重复利用的目的, 以减少代码书写量。
书写格式
无参数无返回值 def __函数名__(): __语句__
无参数有返回值 def __函数名__(): __语句__ return __返回值__
有参数、含默认值的参数,有返回值 def __函数名__(__参数1__, __参数2__=__默认值__): __语句__ return __返回值__
可变参数的列表 def __函数名__(*argvs): __语句__ for i in argvs: __语句__ return __返回值__
可变参数字典 def __函数名__(**kwargvs): __语句__ print kwargvs['key'] return __返回值__
例子
打印一串星星 In [11]: def stars(n=8): ....: for i in range(n): ....: print('*'), ....: ....: In [13]: stars(3) * * * In [14]: stars(9) * * * * * * * * * In [21]: stars() * * * * * * * *
重复某一符号多次 In [15]: def repeat(ch,times): ....: return ch*times ....: In [16]: repeat('*',10) Out[16]: '**********' In [17]: repeat('-',5) Out[17]: '-----'
求所有参数的和 In [18]: def sum(*argvs): ....: s=0 ....: for i in argvs: ....: s+=i ....: return s ....: In [19]: sum(1,2,3) Out[19]: 6 In [20]: sum(1,2,3,4,5,6) Out[20]: 21
调用和显示不同类型的参数 In [23]: def fun(s,n=9,*argvs,**kwargvs): ....: print s,n,argvs,kwargvs ....: ....: In [25]: fun(0) 0 9 () {} In [26]: fun(0,6) 0 6 () {} In [27]: fun(2,5,'asd',3,key=55) 2 5 ('asd', 3) {'key': 55}
lambda函数
单行函数,通常用于一些简单的函数书写。 书写:lambda __参数__:__表达式__
I表示简单的函数 n [5]: f=lambda x:2*x**2+3*x-7 In [6]: f(9) Out[6]: 182 In [7]: f(0) Out[7]: -7 用于map函数内 In [10]: map(lambda x,y:x*y ,range(5),[2,3,7,11,13]) Out[10]: [0, 3, 14, 33, 52]
内建函数
内建函数的名称通常以两个下划线__开始和结束。 通过重写这些函数可以实现一些特殊的功能, 例如运算符重载。
__len__:len函数
__add__ :符号+
__and__:and语句
__mul__:符号*
__neg__:符号-
__str__ :str函数
更多
__int__ __rlshift__ __ror__ __rtruediv__ __add__ __getslice__ __isub__ __str__ __reduce__ __neg__ __radd__ __and__ __truediv__ __rrshift__ __rsub__ __rdiv__ __rmul__ __rmod__ __getnewargs__ __lt__ __init__ __float__ __rshift__ __rand__ __setattr__ __reduce_ex__ __iand__ __invert__ __contains__ __or__ __enter__ __class__ __cmp__ __abs__ __index__ __rfloordiv__ __rpow__ __ixor__ __doc__ __len__ __mul__ __ne__ __rdivmod__ __exit__ __getitem__ __ior__ __coerce__ __getattribute__ __format__ __setitem__ __subclasshook__ __pos__ __pow__ __lshift__ __gt__ __hex__ __oct__ __delslice__ __eq__ __rxor__ __sizeof__ __new__ __delitem__ __reversed__ __nonzero__ __imul__ __trunc__ __setslice__ __mod__ __iter__ __iadd__ __xor__ __delattr__ __div__ __le__ __repr__ __floordiv__ __hash__ __sub__ __long__ __ge__ __divmod__
类
类是属性和方法(函数)的集合
类的写法
简单写法
class __类名__: def __函数名__(self): __语句__
示例 In [56]: class b: ....: def k(self): ....: print 'sasd' ....: ....: In [58]: a=b() In [59]: a.k() sasd
较完整写法
class __类名__: def __init__(self,__参数列表__): #初始化函数,可以接受初始化参数 self.属性1=值1 def __函数__(self,__参数列表__): __语句__
示例 In [67]: class b: ....: def __init__(self,n=5): ....: self.n=n ....: def mprint(self,): ....: for i in range(self.n): ....: print '*', In [68]: a=b(8) In [69]: a.n Out[69]: 8 In [70]: a.mprint() * * * * * * * * In [71]: a.n=3 In [72]: a.mprint() * * *
继承和多态
继承
继承可以大大减少代码的书写量。一个类继承了 父类后,将能调用父类的函数与属性值。并能通过 增加新的函数来扩展功能。 书写: class __类名__(父类名称): def __init__(self,__参数列表1__): 父类名称.__init__(self,__参数列表2__): self.属性1=值1 def __函数__(self,__参数列表__): __语句__
示例 In [73]: class c(b): ....: def __init__(self): ....: b.__init__(self,n=5) ....: self.char='-' ....: def cprint(self,): ....: print self.char In [74]: a=c() In [75]: a.mprint() * * * * * In [76]: a.n Out[76]: 5 In [77]: a.cprint() -
多态
继承父类后,通过增加新的函数,或复写旧有 函数来扩展或改变功能,称为类的多态。
# -*- coding: utf-8 -*- class animal: legs=4 def __init__(self,kind): self.kind=kind def sound(self): print 'Miao' def breath(self): pass class cat(animal): def __init__(self): animal.__init__(self,'cat') self.food='fish' c=cat() print c.legs,c.kind,c.food c.sound() # 4 cat fish # Miao class dog(animal): def __init__(self): animal.__init__(self,'dog') self.food='bone' def sound(self): print 'Woofu' d=dog() print d.legs,d.kind,d.food d.sound() # 4 dog bone # Woofu
文件类file
表示方法
打开文件文件类 f=open/file(__文件名__,__模式__) 文件名是一个字符串 模式也字符,包括w,r,a,+,b等组成的组合 w:写 r:读入 b:二进制模式 a:添加 +:读写模式
示例
只读取文件 a=open('a.txt','r')
清空已有文件供写入 a=open('a.txt','w')
写入时添加到尾部 a=open('a.txt','a')
读取已有文件并可以写入 a=open('a.txt','r+')
二进制读入 a=open('a.txt','rb')
操作
读read
读入所有行readlines
写write
关闭close
移动指针seek
指针位置tell
迭代器iter
迭代器是一种特殊类型,它具有序列一样的可用于循环的性质。 同时又只在调用的时候才会占用内存,所以是一种比较有用的 结构,尤其在处理较大数据的时候。
In [32]: s={1:3,4:5,6:7} In [33]: items=s.iteritems() In [35]: items Out[35]: <dictionary-itemiterator object at 0x025952A0> 用于循环 In [36]: for i in items: ....: print i, (1, 3) (4, 5) (6, 7) 转化为列表 In [37]: items=s.iteritems() In [38]: list(items) Out[38]: [(1, 3), (4, 5), (6, 7)
特殊函数
生成器
生成器通过在循环中加入yield语句, 来达到控制循环进程的目的, 从而使函数表现为一个迭代器。 可以有效的减少内存资源占用。
In [6]: def f(n): ...: for i in range(n): ...: yield i In [7]: a=f(6) In [8]: a Out[8]: <generator object f at 0x025675F8> 转化为列表: In [9]: list(a) Out[9]: [0, 1, 2, 3, 4, 5] In [16]: a=f(6) 使用for循环输出: In [17]: for i in a: ....: print i, 0 1 2 3 4 5
闭包
闭包是是指将所有的参数都书写进一个函数的内部, 而不在全局变量中做更多声明。闭包形式更加利于 代码的重用和移植。闭包形式常常使用函数/类的嵌套 声明。
快速生成不同的一元二次方程函数 In [7]: def fun(a,b,c): ...: def f(x): ...: return a*x**2+b*x+c ...: return f In [8]: f1=fun(3,5,8) #3x^2+5x+8 In [9]: f1(9) Out[9]: 296 In [10]: f1(0) Out[10]: 8 In [11]: f2=fun(1,0,0) #x^2 In [12]: f2(3) Out[12]: 9 In [13]: f2(5) Out[13]: 25
装饰器
装饰器实质上是一种对函数/类进行重新包装,并返回一个新函数/类的操作。
一个显示函数参数的装饰器 In [45]: def show(fun): ....: def new_fun(*argvs,**kwargvs): ....: print argvs,kwargvs ....: return fun(*argvs,**kwargvs) ....: return new_fun #使用装饰器时,要在新函数的声明前用@装饰器名 In [46]: @show ....: def f(a,b,c): ....: return a*b*c In [47]: f(2,3,4) (2, 3, 4) {} Out[47]: 24 In [48]: @show ....: def g(a,n=8): ....: return a*n In [49]: g('*') ('*',) {} Out[49]: '********' In [50]: g('*',5) ('*', 5) {} Out[50]: '*****' In [51]: g('*',n=5) ('*',) {'n': 5} Out[51]: '*****'
模块/库
什么是模块/库
模块是一系列具有某些功能的 类和/或函数的集合,通常是一 个.py文件或多个。
库。或称为包,是一个或 多个模块的集合。通常是 一个文件夹。结构: 库文件夹 --__子文件夹__ --__init__.py --__模块1__.py
导入模块、库
import name
import name as new_name
from name import * from name import something from name.sub import somthing
常用模块/库
错误和异常
断言assert
用法: assert __真值表达式__ 作用:用来验证运行中 一些条件是否得到正确 的结果,有时候用 assert可以方便地找到 错误出现的地方。断言 出错会出现错误。
assert (1+1)==2
try except
用来捕获异常: try: __运行语句__ except [__异常名称__,[__变量名__]]: __异常处理语句__
try: __运行语句__ except: __异常处理语句__ finally: __无论如何都执行__
In [4]: try: ...: a=[5,3] ...: print a[6] ...: except: ...: print 'Error' #会出现索引错误 Error
raise
主动抛出异常错误。 写法raise __错误名称__,__提示内容__
In [7]: if 1+1!=1: ...: raise ValueError,'something is wrong' ...: ValueError Traceback (most recent call last) ValueError: something is wrong
常见错误类型
AssertionError断言错误
EOFError文件末尾
IOError读写错误
IndexError索引值错误
KeyError键名错误
KeyboardInterrupt键盘打断
MemoryError内存错误
NameError名称错误
StopIteration迭代终止
SyntaxError语法错误
IndentationError缩进错误
SystemError系统错误
SystemExit系统错误
TypeError类型错误
代码结构
代码文件
.py
.pyw
.pyc/pyo/pyd
注释#
注释在代码中起解释说明的作用,在执行时将被忽略。 每一行(包括行尾)以#开始的文字将被忽略。字符串中的#不包括。
系统使用注释,在文件开始使用
环境路径
Linux系统下的环境设置 #!/usr/bin/python
声明文件编码
#encoding:utf-8
# -*- coding: utf-8 -*-
变量名和关键字
变量名规则
1. 变量名由大小写字母、数字、下划线组成
2. 变量名不能以数字开始
3. 变量名不能是关键字
4. 变量名严格区分大小写
5. 举例
符合规则的
a
my_name
block23
__file_name
不符合规则的
if
2k
to-day
关键字
关键字又称保留字,是用于控制程序运行所需要的 一些特殊词语。如if while for import return def class 等
可见于keyword模块kwlist
代码块/缩进
代码块通常是对不同结构下的一部分代码的称呼。 例如下图中,橙色紫色和绿色分别代表了三个不同的代码块:
缩进是指代码前面的几个空格或制表符,以使代码看起来向后靠。 Python用缩进量来区分代码块,相同的代码块必须具有相同的缩进量。 通常的代码编辑器都具有自动缩进功能。通常使用4个空格作为一个缩进量。
__main__
__main__是用来标识一个文件是导入的(import), 还是作为主程序运行的。通常在.py文件的结尾处加上 if __name__=="__main__": main() 这段代码通常用与一些有独立运行功能的模块的运行。
文档doc
文档doc,是另一种对代码的说明。 Python中的文档可以夹杂在代码书写中。 例如在函数或类的声明行下加入以下形式的代码: In [3]: def fun(): ...: 'this is a doc' ...: print 'blah blah' ...: In [4]: fun() blah blah In [6]: fun.__doc__ Out[6]: 'this is a doc' __doc__可用于自动生成模块文档。 可以大大简化文档书写的工作量。