2022年python基础语法培训课件_第1页
2022年python基础语法培训课件_第2页
2022年python基础语法培训课件_第3页
2022年python基础语法培训课件_第4页
2022年python基础语法培训课件_第5页
已阅读5页,还剩29页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、此文档仅供收集于网络,如有侵权请联系网站删除Python 的特点 1. 简洁 Python 是一种代表简洁思想的语言;2. 易学 Python 有极其简洁的语法;3. 免费、开源Python 是 FLOSS (自由 /开放源码软件)之一;4. 高层语言使用 Python 编写程序时无需考虑如何治理程序使用的内存一类的底层细节;5. 可移植性Python 已被移植到许多平台,这些平台包括 AROS 、AS/400、Linux 、Windows 、FreeBSD、Macintosh 、Solaris、OS/2、Amiga 、BeOS、OS/390、z/OS、Palm OS、QNX 、VMS 、Ps

2、ion、Acom RISC OS 、 VxWorks 、PlayStation、 Sharp Zaurus、Windows CE 甚至仍有 PocketPC;6. 说明性可以直接从源代码运行;在运算机内部,成运算机使用的机器语言;7. 面对对象python 说明器把源代码转换为字节码的中间形式,然后再把它翻译Python 既支持面对过程编程也支持面对对象编程;8. 可扩展性部分程序可以使用其他语言编写,如 c/c+;9. 可嵌入型 可以把 Python 嵌入到 c/c+ 程序中,从而供应脚本功能;10. 丰富的库只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除Python 标准库的确

3、很巨大;它可以帮忙你处理各种工作,包括正就表达式、文档生成、单元测试、线程、数据库、网页浏览器、CGI 、FTP、GUI (图形用户界面)、Tk 和其他与系统有关的电子邮件、 XML 、XML-RPC 、 HTML 、WAV 文件、密码系统、操作;- 分割线 -以下是 Python 的基本语法 - 一、基本概念1. python 中数有四种类型:整数、长整数、浮点数和复数;整数,如 1 长整数 是比较大的整数浮点数 如 1.23、3E-2 复数 如 1 + 2j 、 1.1 + 2.2j 2. 字符串(字符的序列)python 中单引号和双引号使用完全相同;使用三引号 或 可以指定一个多行字符

4、串;转义符 通过在字符串前加r 或 R; 如 rthis is a line with n 就n 会显示,并不是换行;自然字符串,python 答应处理 unicode 字符串,加前缀 字符串是不行变的;u 或 U, 如 uthis is an unicode string ;按字面意义级联字符串,如this is string会被自动转换为this is string ;3. 标识符的命名第一个字符必需是字母表中字母或下划线 _;标识符的其他的部分有字母、数字和下划线组成;标识符对大小写敏锐;4. 对象 python 程序中用到的任何“ 东西” 都成为“ 对象” ;5. 规律行和物理行物理行

5、是我们在编写程序时看到的,规律行就是 python 看到的;python 中分号 ;标识一个规律行的终止,但是实际中一般每个物理行只写一个规律行,可以防止使用分号;多个物理行中可以写一个规律行,如下:s = peter is writing this article 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除上面 的使用被称为明确的行连接,又如:print peter 6. 缩进空白在 python 是特别重要的,行首的空白是最重要的,又称为缩进;行首的空白(空格和制表符)用来打算规律行的缩进层次,从而打算语句分组;这意味着同一层次的语句必需有相同的缩进,每一组这样的语句称为一

6、个块;留意:不要混合使用空格和制表符来缩进,由于在跨过不同的平台时无法正常工作;二、运算符与表达式1. 运算符与其用法运算符 名称 说明 例子+ 加 两个对象相加 3 + 5 得到 8;a + b得到 ab;- 减 得到负数或是一个数减去另一个数-5.2 得到一个负数;50 - 24 得到 26;* 乘 两个数相乘或是返回一个被重复如干次的字符串 2 * 3 得到 6;la * 3 得到 lalala ;* 幂返回 x 的 y 次幂3 * 4 得到 81(即 3 * 3 * 3 * 3 )/ 除 x 除以 y 4/3 得到 1(整数的除法得到整数结果);4.0/3 或 4/3.0 得到 1.3

7、333333333333333 / 取整除 返回商的整数部分 4 / 3.0 得到 1.0 % 取模 返回除法的余数 8%3 得到 2;-25.5%2.25 得到 1.5 左移 把一个数的比特向左移肯定数目(每个数在内存中都表示为比特或二进制数字,即 0 和 1) 2 右移 把一个数的比特向右移肯定数目 11 1 得到 5; 11 按比特表示为 1011,向右移动 1 比特后得到101,即十进制的 5;& 按位与 数的按位与 5 & 3 得到 1;| 按位或 数的按位或 5 | 3 得到 7; 按位异或 数的按位异或 5 3 得到 6 按位翻转 x 的按位翻转是 -x+1 5 得到 6; 小于

8、 返回 x 是否小于 y;全部比较运算符返回 1 表示真,返回 0 表示假;这分别与特殊的变量 True 和 False等价;留意,这些变量名的大写;5 3 返回 0(即 False)而 3 5 返回 1(即 True);比较可以被任意连接:3 5 大于 返回 x 是否大于 y 5 3 返回 True;假如两个操作数都是数字,它们第一被转换为一个共同的类型;否就,它总是返回 False;= 小于等于 返回 x 是否小于等于 y x = 3; y = 6; x = 大于等于 返回 x 是否大于等于 y x = 4; y = 3; x = y 返回 True;= 等于 比较对象是否相等 x = 2

9、; y = 2; x = y 返回 True;x = str; y = stR; x = y 返回 False;x = str; y = str; x = y 返回 True;.= 不等于比较两个对象是否不相等x = 2; y = 3; x .= y返回 True;只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除not 布尔“ 非”假如 x 为 True,返回 False;假如 x 为 False,它返回 True; x = True; not y 返回 False;and 布尔“ 与”假如 x 为 False,x and y 返回 False,否就它返回 y 的运算值;x = Fa

10、lse; y = True; x and y,由于 x是 False,返回 False;在这里, Python 不会运算 y,由于它知道这个表达式的值确定是 False(由于 x 是 False);这个现象称为短路运算;or 布尔“ 或”假如 x 是 True,它返回 True,否就它返回y 的运算值;x = True; y = False; x or y返回 True;短路运算在这里也适用;2. 运算符优先级(从低到高)运算符 描述lambda Lambda 表达式or 布尔“ 或”and 布尔“ 与”not x 布尔“ 非”in, not in 成员测试is,is not 同一性测试, =

11、,.= ,= 比较| 按位或 按位异或& 按位与 移位+,- 加法与减法*,/,% 乘法、除法与取余+x,-x 正负号x 按位翻转* 指数x.attribute 属性参考xindex 下标xindex:index 寻址段farguments. 函数调用experession,. 绑定或元组显示expression,. 列表显示key:datum,. 字典显示expression,. 字符串转换3. python 掌握台输出 使用 print print abc #打印 abc 并换行print abc%s % d #打印 abcd print abc%sef%s % d, g #打印 abcd

12、efg 三、掌握流1. if 语句i = 10 n = intraw_inputenter a number: 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除if n = i: print equal elif n 删除一个变量 /名称, del 之后,该变量就不能再使用;六、数据结构python 有三种内建的数据结构:列表、元组和字典;1. 列表list 是处理一组有序项目的数据结构,列表是可变的数据结构;列表的项目包含在方括号 中,eg: 1, 2, 3 , 空 列表 ;判定列表中是否包含某项可以使用 in, 比如 l = 1, 2, 3; print 1 in l; #Tru

13、e;支持索引和切片操作;索引时如 超出范畴,就 IndexError ;使用函数 len查看长度;使用 del 可以删除列表中的项,eg: del l0 # 假如超出范畴,就 IndexError list 函数如下:append(value)-向列表尾添加项value l = 1, 2, 2 l.append3 #1, 2, 2, 3 countvalue-返回列表中值为value 的项的个数l = 1, 2, 2 print l.count2 # 2 extendlist2-向列表尾添加列表list2 l = 1, 2, 2 l1 = 10, 20 l.extendl1 print l #

14、1, 2, 2, 10, 20 -返回列表中第一个显现的值为value 的索引,假如没有,就反常ValueError indexvalue, start, stopl = 1, 2, 2 a = 4 try: print l.indexa 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除except ValueError, ve: print there is no %d in list % a inserti, value-向列表 i 位置插入项vlaue,假如没有i,就添加到列表尾部l = 1, 2, 2 l.insert1, 100 print l #1, 100, 2, 2

15、l.insert100, 1000 print l #1, 100, 2, 2, 1000 popi-返回 i 位置项,并从列表中删除;假如不供应参数,就删除最终一个项;假如供应,但是i 超出索引范畴,就反常IndexError l = 0, 1, 2, 3, 4, 5 print l.pop # 5 print l #0, 1, 2, 3, 4 print l.pop1 #1 print l #0, 2, 3, 4 try: l.pop100 except IndexError, ie: print index out of range removevalue-删除列表中第一次显现的valu

16、e,假如列表中没有vlaue,就反常 ValueError l = 1, 2, 3, 1, 2, 3 l.remove2 print l #1, 3, 1, 2, 3 try: l.remove10 except ValueError, ve: print there is no 10 in list reverse-列表反转l = 1, 2, 3 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除l.reverse print l #3, 2, 1 sortcmp=None, key=None, reverse=False-列表排序【Python Library Reference

17、】cmp:cmp specifies a custom comparison function of two arguments iterable elements which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmpx.lower, y.lower key:key spe

18、cifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower reverse:reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.In general, the key and reverse conversion processes are much fas

19、ter than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. l5 = 10, 5, 20, 1, 30 l5.sort print l5 #1, 5, 10, 20, 30 l6 = bcd, abc, cde, bbb l6.sortcmp = lambda s1, s2: cmps10,s21 print l6 #abc

20、, bbb, bcd, cde l7 = bcd, abc, cde, bbb, faf l7.sortkey = lambda s: s1 print l7 #faf, abc, bbb, bcd, cde 2. 元组tuple 和 list 特别相像,但是 tuple 是不行变的,即不能修改 tuple,元组通过圆括号中用逗号分割的项定义;支持索引和切片操作;可以使用 in 查看一个元素是否在 tuple 中;空元组 ;只含有一个元素的元组 a, # 需要加个逗号优点: tuple 比 list 速度快;对不需要修改的数据进行写爱护,可以是代码更安全tuple 与 list 可以相互转换,

21、使用内置的函数 list 和 tuple ;l = 1, 2, 3 print l # 1, 2, 3 t = tuplel print t # 1, 2, 3 l1 = listt 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除print l1 #1, 2, 3 元组最通常的用法是用在打印语句,如下例:name = Peter Zhang age = 25 print Name: %s; Age: %d % name, age # Name: Peter Zhang; Age: 25 函数如下:countvalue-返回元组中值为value 的元素的个数t = 1, 2, 3,

22、1, 2, 3 print t.count2 # 2 indexvalue, start, stop-返回列表中第一个显现的值为value 的索引,假如没有,就反常ValueError t = 1, 2, 3, 1, 2, 3 print t.index3 # 2 try: print t.index4 except ValueError, ve: print there is no 4 in tuple # there is no 4 in tuple 3. 字典字典由键值对组成,键必需是唯独的;eg: d = key1:value1, key2:value2;空字典用 表示;字典中的键值对

23、是没有次序的,假如想要一个特定的次序,那么使用前需要对它们排序;dkey = value,假如字典中已有key,就为其赋值为value,否就添加新的键值对key/value ;使用 del dkey 可以删除键值对;判定字典中是否有某键,可以使用in 或 not in ;d = d1 = one d2 = two d3 = three del d3 for key, value in d.items: print %s - %s % key, value 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除 #1 - one #2 - two dict 函数如下 : clear-删除字典

24、中全部元素d1 = 1:one, 2:two d1.clear print d1 # copy-返回字典的一个副本浅复制 d1 = 1:one, 2:two d2 = d1.copy print d2 #1: one, 2: two dict.fromkeysseq,val=None - 创建并返回一个新字典,以序列seq 中元素做字典的键,val 为字典全部键对应的初始值 默认为 None l = 1, 2, 3 t = 1, 2, 3 d3 = .fromkeysl print d3 #1: None, 2: None, 3: None d4 = .fromkeyst, default p

25、rint d4 #1: default, 2: default, 3: default getkey,default- 返回字典dict 中键 key 对应值,假如字典中不存在此键,就返回default 的值 default默认值为 None d5 = 1:one, 2:two, 3:three print d5.get1 #one print d5.get5 #None print d5.get5, test #test has_keykey-判定字典中是否有键key d6 = 1:one, 2:two, 3:three print d6.has_key1 #True 键, 值对元组的列表p

26、rint d6.has_key5 #False items-返回一个包含字典中只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除d7 = 1:one, 2:two, 3:three for item in d7.items: print item #1, one #2, two #3, three for key, value in d7.items: print %s - %s % key, value #1 - one #2 - two #3 - three keys-返回一个包含字典中全部键的列表d8 = 1:one, 2:two, 3:three for key in d8.k

27、eys: print key #1 #2 #3 values-返回一个包含字典中全部值的列表d8 = 1:one, 2:two, 3:three for value in d8.values: print value #one #two #three popkey, default-如字典中key 键存在,删除并返回dictkey ,如不存在,且未给出default 值,引发KeyError 反常d9 = 1:one, 2:two, 3:three print d9.pop1 #one print d9 #2: two, 3: three print d9.pop5, None #None t

28、ry: 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除d9.pop5 # raise KeyError except KeyError, ke: print KeyError:, ke #KeyError:5 popitem-删除任意键值对,并返回该键值对,假如字典为空,就产生反常 KeyError d10 = 1:one, 2:two, 3:three print d10.popitem #1, one - 如字典中有key,就返回 vlaue 值,如没有key,就加上该key,值为 default,默print d10 #2: two, 3: three setdefaultk

29、ey,default认 None d = 1:one, 2:two, 3:three print d.setdefault1 #one print d.setdefault5 #None print d #1: one, 2: two, 3: three, 5: None print d.setdefault6, six #six print d #1: one, 2: two, 3: three, 5: None, 6: six dict 中去,键字重复时会掩盖dict 中的键值updatedict2-把 dict2 的元素加入到d = 1:one, 2:two, 3:three d2 =

30、1:first, 4:forth d.updated2 print d #1: first, 2: two, 3: three, 4: forth viewitems-返回一个 view 对象,( key, value)pair 的列表,类似于视图;优点是,假如字典发生变化,view 会同步发生变化;在迭代过程中,字典不答应转变,否就会报反常d = 1:one, 2:two, 3:three for key, value in d.viewitems: print %s - %s % key, value #1 - one #2 - two #3 - three viewkeys-返回一个 v

31、iew 对象, key 的列表d = 1:one, 2:two, 3:three for key in d.viewkeys: print key #1 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除#2 #3 viewvalues-返回一个view 对象, value 的列表d = 1:one, 2:two, 3:three for value in d.viewvalues: print value #one #two #three 4. 序列序列类型是指容器内的元素从 0 开头的索引次序拜访,一次可以拜访一个或者多个元素;列表、元组和字符串都是序列;序列的两个主要特点是索引操

32、作符和切片操作符;索引可以得到特定元素;切片可以得到部分序列;1 numbers = zero, one, two, three, four 2 3 print numbers1 # one 4 print numbers-1 # four 5 #print numbers5 # raise IndexError 6 7 print numbers: # zero, one, two, three, four 8 print numbers3: # three, four 9 print numbers:2 # zero, one 10 print numbers2:4 # two, thre

33、e 11 print numbers1:-1 # one, two, three 切片操作符中的第一个数(冒号之前) 表示切片开头的位置,其次个数 (冒号之后) 表示切片到哪里终止;如 果不指定第一个数,Python 就从序列首开头;假如没有指定其次个数,就 Python 会停止在序列尾;留意,返回的序列从开头位置 开头 ,刚好 在终止位置之前 终止;即开头位置是包含在序列切片中的,而终止位置被排斥在切片外;5. 绑定可以用负数做切片;负数用在从序列尾开头运算的位置;当创建一个对象并给它赋一个变量的时候,这个变量仅仅“ 指向” 那个对象,而不是表示这个对象本身!也 就是说,变量名指向运算机中储

34、备那个对象的内存,这被称作名称到对象的绑定;假如要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简洁对象),那么必需使用切 片操作符来取得拷贝;只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除 七、面对对象编程python 支持面对对象编程;类和对象是面对对象编程的两个主要方面,类创建一个新的类型,对象是这个类的实例;对象可以使用一般的属于对象的变量储备数据,属于对象或类的变量被称为域;对象也可以使用属于类的函数,这样的函数称为类的方法;域和方法可以合称为类的属性;域有两种类型 -属于实例的或属于类本身;它们分别被称为实例变量和类变量;类使用关键字 class 创建,

35、类的域和方法被列在一个缩进块中;类的方法必需有一个额外的第一个参数,但是在调用时不为这个参数赋值,这个特殊变量指对象本身,依据惯例它的名称是 self,类似 C#中的 this;class Animal: pass #empty block _init_ 方法 在类的一个对象被创建时调用该方法;相当于 c+中的构造函数;_del_方法 在类的对象被销毁时调用该方法;相当于 c+中的析构函数; 在使用 del 删除一个对象时也就调用_del_方法;Python 中全部的类成员包括数据成员 都是 public 的;只有一个例外, 假如使用的数据成员以双下划线为前缀,就为私有变量;class Per

36、son: Count = 0 def _init_self, name, age: Person.Count += 1 = name self._age = age p = Personpeter, 25 p1 = Personjohn, 20 print Person.Count #2 print #peter print p._age #AttributeError: Person instance has no attribute _age 继承:为了使用继承,基类的名称作为一个元组跟在类名称的后面;的例子:1 class SchoolMember: 2 Represent any sc

37、hool member. 只供学习与沟通python 支持多重继承;下面是一个关于继承此文档仅供收集于网络,如有侵权请联系网站删除3 def _init_self, name, age: 4 = name 5 self.age = age 6 print Initializing a school member. 7 8 def tellself: 9 Tell my details 10 print Name: %s, Age: %s, % , self.age, 11 12 class TeacherSchoolMember: 13 Represent a teacher. 14 def

38、_init_self, name, age, salary: 15 SchoolMember._init_self, name, age 16 self.salary = salary 17 print Initializing a teacher 18 19 def tellself: 20 SchoolMember.tellself 21 print Salary: %d % self.salary 22 23 class StudentSchoolMember: 24 Represent a student. 25 def _init_self, name, age, marks: 26

39、 SchoolMember._init_self, name, age 27 self.marks = marks 28 print Initializing a student 29 30 def tellself: 31 SchoolMember.tellself 32 print Marks: %d % self.marks 33 34 print SchoolMember._doc_ 35 print Teacher._doc_ 36 print Student._doc_ 37 38 t = TeacherMr. Li, 30, 9000 39 s = StudentPeter, 2

40、5, 90 40 41 members = t, s 42 43 for m in members: 44 m.tell 程序输出如下:只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除Represent any school member. Represent a teacher. Represent a student. Initializing a school member. Initializing a teacher Initializing a school member. Initializing a student Salary: 9000 Name: Mr. Li,

41、 Age: 30, Name: Peter, Age: 25, Marks: 90 八、输入 /输出程序与用户的交互需要使用输入/输出,主要包括掌握台和文件;对于掌握台可以使用raw_input 和 print,也可使用 str 类; raw_inputxxx 输入 xxx 然后读取用户的输入并返回;1. 文件输入 /输出可以使用 file 类打开一个文件,使用 file 的 read、readline 和 write 来恰当的读写文件;对文件读写才能取决于打开文件时使用的模式,常用模式有读模式 r 、写模式 w 、追加模式 a ,文件操作之后需要调用1 test = 2 This is a

42、program about file I/O. 3 4 Author: Peter Zhange 5 Date: 2022/12/25 6 7 close 方法来关闭文件;8 f = filetest.txt, w # open for writing, the file will be created if the file doesnt exist 9 f.writetest # write text to file 10 f.close # close the file 11 12 f = filetest.txt # if no mode is specified, the defau

43、lt mode is readonly. 13 14 while True: 15 line = f.readline # zero length indicates the EOF of the file 16 if lenline = 0: 17 break 18 print line, 19 20 f.close 2. 储备器只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除python 供应一个标准的模块,成为 pickle ,使用它可以在一个文件中储备任何 python 对象,之后可以完整的取出来,这被称为长久地储备对象;仍有另外一个模块成为 cPickle ,它的功能和 p

44、ickle 完全一样,只不过它是用 c 写的,要比 pickle 速度快 大约快 1000 倍;import cPickle datafile = data.data namelist = peter, john, king f = filedatafile, w cPickle.dumpnamelist, f f.close del namelist f = filedatafile storednamelist = cPickle.loadf print storednamelist #peter, john, king 九、反常当程序中显现某些反常的状况时,反常就发生了;python 中

45、可以使用try . except 处理;try: print 1/0 except ZeroDivisionError, e: print e except: print error or exception occurred. #integer division or modulo by zero 可以让 try . except 关联上一个 else,当没有反常时就执行 else;我们可以定义自己的反常类,需要继承 Error 或 Exception;class ShortInputExceptionException: A user-defined exception class def

46、 _init_self, length, atleast: Exception._init_self 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除self.length = length self.atleast = atleast try: s = raw_inputenter someting- if lens 3: raise ShortInputExceptionlens, 3 except EOFError: print why you input an EOF. except ShortInputException, ex: print The lenght of i

47、nput is %d, was expecting at the least %d % ex.length, ex.atleast else: print no exception #The lenght of input is 1, was expecting at the least 3 try.finally try: f = filetest.txt while True: line = f.readline if lenline = 0: break time.sleep2 print line, finally: f.close print Cleaning up. 十、 Pyth

48、on 标准库Python 标准库是随 Pthon 附带安装的,包含了大量极其有用的模块;1. sys 模块 sys 模块包含系统对应的功能sys.argv-包含命令行参数,第一个参数是 py 的文件名 sys.platform-返回平台类型 sys.exitstatus- 退出程序,可选的 status范畴: 0-127:0 表示正常退出,其他表示不正常,可抛反常大事供捕 获sys.path-程序中导入模块对应的文件必需放在sys.path 包含的目录中,使用sys.path.append 添加自己的模块路径sys.modules-This is a dictionary that maps

49、module names to modules which have already been loaded sys.stdin,sys.stdout,sys.stderr-包含与标准 I/O 流对应的流对象 s = sys.stdin.readline 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除sys.stdout.writes 2. os 模块该模块包含普遍的操作系统功能Windows,它是 nt,而对于 Linux/Unix用户,它是 posix 字符串指示你正在使用的平台;比如对于os.getcwd函数得到当前工作目录,即当前Python 脚本工作的目录路径os.get

50、env和 os.putenv函数分别用来读取和设置环境变量 os.listdir 返回指定目录下的全部文件和目录名 os.remove函数用来删除一个文件 os.system函数用来运行 shell 命令os.linesep 字符串给出当前平台使用的行终止符;例如,os.sep 操作系统特定的路径分割符 os.path.split 函数返回一个路径的目录名和文件名Windows 使用 rn,Linux 使用 n而 Mac 使用 r os.path.isfile 和 os.path.isdir函数分别检验给出的路径是一个文件仍是目录os.path.existe函数用来检验给出的路径是否真地存在十

51、一、其他1. 一些特殊的方法名称 说明_init_self,. 这个方法在新建对象恰好要被返回使用之前被调用;_del_self 恰好在对象要被删除之前调用;_str_self 在我们对对象使用 print 语句或是使用 str的时候调用;_lt_self,other 当使用 小于 运算符( 等等)都有特殊的方法;_getitem_self,key 使用 xkey 索引操作符的时候调用;_len_self 对序列对象使用内建的 len函数的时候调用;下面的类中定义了上表中的方法:class Array: _list = def _init_self: print constructor def

52、 _del_self: print destructor def _str_self: return this self-defined array class def _getitem_self, key: return self._listkey def _len_self: return lenself._list 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除def Addself, value: self._list.appendvalue def Removeself, index: del self._listindex def DisplayItemsself: p

53、rint show all items- for item in self._list: print item arr = Array #constructor print arr #this self-defined array class print lenarr #0 arr.Add1 arr.Add2 arr.Add3 print lenarr #3 print arr0 #1 arr.DisplayItems #show all items- #1 #2 #3 arr.Remove1 arr.DisplayItems #show all items- #1 #3 #destructo

54、r 2. 综合列表通过列表综合,可以从一个已有的列表导出一个新的列表;list1 = 1, 2, 3, 4, 5 list2 = i*2 for i in list1 if i 3 print list1 #1, 2, 3, 4, 5 print list2 #8, 10 3. 函数接收元组 /列表 /字典当函数接收元组或字典形式的参数的时候,有一种特殊的方法,使用 数量的参数的时候特殊有用;只供学习与沟通*和* 前缀;该方法在函数需要猎取可变此文档仅供收集于网络,如有侵权请联系网站删除由于在 args 变量前有 * 前缀,全部余外的函数参数都会作为一个元组储备在args 中;假如使用的是*

55、前缀,余外的参数就会被认为是一个字典的键 /值对;def powersumpower, *args: total = 0 for i in args: total += powi, power return total print powersum2, 1, 2, 3 #14 def displaydic*args: for key,value in args.items: print key:%s;value:%s % key, value displaydica=one, b=two, c=three #key:a;value:one #key:c;value:three #key:b;v

56、alue:two 4. lambda lambda 语句被用来创建新的函数对象,并在运行时返回它们;为函数体,而表达式的值被这个lambda 需要一个参数,后面仅跟单个表达式作新建的函数返回;留意,即便是print 语句也不能用在lambda 形式中,只能使用表达式;func = lambda s: s * 3 print funcpeter #peter peter peter func2 = lambda a, b: a * b print func22, 3 #6 5. exec/eval exec 语句用来执行储存在字符串或文件中的Python 语句;eval 语句用来运算储备在字符串

57、中的有效Python 表达式;cmd = print hello world exec cmd #hello world 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除expression = 10 * 2 + 5 print evalexpression #25 6. assert assert语句用来断言某个条件是真的,并且在它非真的时候引发一个错误-AssertionError ;flag = True assert flag = True try: assert flag = False except AssertionError, err: print failed el

58、se: print pass 7. repr 函数repr 函数用来取得对象的规范字符串表示;反引号(也称转换符)可以完成相同的功能;留意,在大多数时候有 evalreprobject = object ;可以通过定义类的 _repr_方法来掌握对象在被 repr 函数调用的时候返回的内容;arr = 1, 2, 3 print arr #1, 2, 3 print reprarr #1, 2, 3 十二、练习实现一个通讯录,主要功能:添加、删除、更新、查询、显示全部联系人;1 import cPickle 2 import os 3 import sys 4 5 class Contact:

59、 6 def _init_self, name, phone, mail: 7 = name 8 self.phone = phone 9 self.mail = mail 10 11 def Updateself, name, phone, mail: 只供学习与沟通此文档仅供收集于网络,如有侵权请联系网站删除12 = name 13 self.phone = phone 14 self.mail = mail 15 16 def displayself: 17 print name:%s, phone:%s, mail:%s % , self.phone, self.mail 18 19 20 #

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论