资源简介
(共89张PPT)
第2章 Python基础
Chap2 Python Basic
Python程序基本构成与风格2.1Python2.1.1 Python程序基本构成Python一个小程序# Filename: prog2-1.py# For loop on a list #第1行num= [1, 2, 3, 4, 5]#第2行prog =int(input('please input the value of prog: '))#第3行fornumberinnum:#第4行prog= prog * number#第5行print('The prog is: ',prog)#第6行FilePython程序基本要素
变量
01
表达式
02
语句
03
Python
Python输入:input()函数>>> price=input('input thestock priceofApple: ')input thestock priceofApple:109>>>price'109'>>>type(price)<class'str'>>>> price =int(input('input the stock price of Apple: '))>>> price =eval(input('input the stock price of Apple: '))Sourceinput()返回的类型是字符型PythonPython输出:print函数Python使用print函数实现输出:print(变量)print(字符串)>>>myString='Hello,World!'>>>print(myString)Hello,World!SourcePython2.1.2 Python程序设计风格PythonPython风格(一)>>># For loop on a list#第1行>>>print('The prog is: ',prog)#第6行Source注释#PythonPython风格(二)缩进030102增加缩进表示语句块的开始Python用相同的缩进表示同级别语句块减少缩进表示语句块的退出# prog2-1.py# For loop on a list#第1行num= [1,2,3,4,5]prog =int(input("please input the value of prog:"))fornumberinnum:prog = prog * numberprint("Theprog is:", prog)SourcePythonPython风格(二)缩进# prog2-1.py# For loop on a list#第1行num= [1,2,3,4,5]prog =int(input("please input the value of prog:"))fornumberinnum:prog = prog * numberprint('The prog is: ', prog)SourcePythonPython风格(三)>>># long sentence>>>if(signal =='red')and\(car =='moving'):car ='stop'elif(signal =='green')and\(car =='stop'):car ='moving'Source>>># long sentence>>>if(signal =='red')and(car =='moving'):car ='stop'elif(signal =='green')and(car =='stop'):car ='moving'Source续行\PythonPython风格(三)无需续行符可直接换行的两种情况:小括号、中括号、花括号的内部可以多行书写三引号包括下的字符串也可以跨行书写>>># triple quotes>>>print('''Hieverybody,welcome toPython’sMOOC course.Here we can learn something aboutPython.Goodluck!''')Source续行\PythonPython风格(四)>>> x ='Today'; y ='is'; z ='Thursday';print(x, y, z)Today is ThursdaySource>>>x ='Today'>>> y ='is'>>> z ='Thursday'>>>print(x, y, z)Today is ThursdaySource一行多语句;PythonPython语法基础2.2Python2.2.1变量Python变量变量引用对象名标识对象>>># variable>>>PI = 3.14159>>> pi ='circumference ratio'>>>print(PI)3.14159>>>print(pi)circumference ratioSourcePython标识符标识符是指Python语言中允许作为变量名或其他对象名称的有效符号首字符是字母或下划线其余可以是字母、下划线、数字大小写敏感(PI和pi是不同的标识符)>>># Identifier>>> PI = 3.14159>>> pi ='circumference ratio'>>>print(PI)3.14159>>>print(pi)circumference ratioSourcePython特殊意义标识符
_cat
__fish
__dog__
一个下划线或两个下划线开头的标识符对解释器来讲是有特殊意义,避免使用这种形式的标识符用作一般的变量名。
Python
关键字关键字是Python语言的关键组成部分,不可随便作为其他对象的标识符在一门语言中关键字是基本固定的集合在IDE中常以不同颜色字体出现>>> import keyword>>> print(keyword.kwlist)FalseNoneTrueandasassertbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyieldPython关键字>>>i = 0>>>whilei < 20:ifi % 2 == 0:print(i)i = i + 1Sourcewhile和if在IDLE中显示为橙色,它们均是关键字Python变量名>>> num = 5>>> salary = 3450.7>>> tax = salary * 5 * 0.15Source变量命名要见名识义num表示人数salary表示薪酬tax表示税额Python变量的使用不同于C语言不需要显式声明变量变量类型不需要专门声明第一次对变量名赋值时自动声明该变量Python变量的使用>>> aTraceback(most recent call last):File "<pyshell#0>", line 1, in <module>aNameError: name 'a' is not defined>>> b = 3.14>>> b3.14>>> c ='Circle'>>> c'Circle'Source变量必须创建和赋值后使用a没有赋值,所以无法直接使用;变量b和c均有赋值;通过赋值号“=”右边的表达式的结果确定左边变量的类型。Python变量的使用变量第一次赋值,同时获得类型和“值”Python是动态的强类型语言不需要显式声明,根据“值”确定类型以“引用”的方式实现赋值>>># Identifier>>> PI = 3.14159>>> pi ='one word'>>>print(PI)3.14159>>>print(pi)one wordSource=3.14159'one word'piPIPython变量的管理动态类型引用计数a = c,指向了相同的数据对象b和a创建的是不同的5.8对象单独id(5.8)是创建的全新的对象5.85.85.8acbPython变量的管理动态类型>>> a = 5.8>>>id(a)1709988157600>>> b = 5.8>>>id(b)1709988157648Source>>>id(5.8)1709988157696>>> c = a>>>id(c)1709988157600>>> c = 3SourcePython变量的管理>>>p = 3>>> q =3>>>pisqTrueSource3.14159PIpi>>>PI =3.14159>>>pi= 3.14159>>> PIispiFalse>>> pi = PI>>>print(PI)3.14159>>>piisPITrueSourceis运算符的基础是id()函数图中的形式用哪个语句可以表示?Python2.2.2表达式和赋值表达式Python表达式用运算符连接各种类型数据的式子就是表达式算术运算符乘方**正负号+ -乘除 */整除//取余%加减+ -位运算符取反~与&或|异或^左移<<右移>>关系运算符小于<大于>小于等于<=大于等于>=等于==不等于!=逻辑运算符非not与and或orPython表达式运算符有优先级顺序表达式必须有运算结果>>># expression>>> PI = 3.14159>>> r = 2>>>c_circ=2 * PI * r>>>print("Thecircle'scircumis",c_circ)Source2*PI*r是表达式运算结果赋值给变量c_circPython赋值 增量赋值>>>#Augmented assignment>>> m = 18>>> m/=5>>> m3.6Source增量赋值操作符m /=5即m = m / 5+=-=*=/=%=**=<<=>>=&=^=|=Python赋值链式赋值>>>#Chainedassignment>>> a = 1>>> b = a = a + 1>>> b2>>> a2Sourceb = a = a + 1相当于如下2条语句:>>> a = a + 1>>> b = aPython赋值 多重赋值等号左右两边都以元组的方式出现>>>#Multiple assignment>>> PI, r = 3.1415, 3>>> PI3.1415>>> r3Source相当于:>>>(PI, r) = (3.14159, 3)Python2.2.3语句Python语句完整执行一个任务的一行逻辑代码赋值语句完成了赋值print()函数调用语句完成了输出>>>#statement>>> PI = 3.14159>>>print(PI)SourcePython语句和表达式完成一个任务如,打印一份文件语句任务中的一个具体组成部分如,这份文件的具体内容表达式PythonPython数据类型2.3Python数据类型必须有明确的数据类型,程序才能给对象分配存储空间,从而进行运算000010001001001110010011100100110000100010011011PythonPython数据类型浮点型元组字符串列表字典复数型布尔型(长)整型Python2.3.1基本类型Python基本类型01(长)整型02布尔型03浮点型04复数型Python整型整型和长整型并不严格区分Python 2支持整型值后加“L”即为长整型>>># integer>>>type(3)<class'int'>SourcePython布尔型整型的子类仅有2个值:True、False本质上是用整型的1、0分别存储的>>>#boolean>>> x =True>>>type(x)<class 'bool'>>>>int(x)1>>> y =False>>>int(y)0SourcePython浮点型即数学中的实数可以类似科学计数法表示>>># float>>> 3.223.22>>> 9.8e39800.0>>> -4.78e-2-0.0478>>>type(-4.78e-2)<class'float'>SourcePython复数型j=,则j是虚数实数+虚数 就是复数虚数部分必须有j>>># complex>>>3j3j>>>type(3j)<class'complex'>>>> 5+0j(5+0j)>>>type(5+0j)<class'complex'>Source>>># complex>>> 2.4+5.6j(2.4+5.6j)>>>type(2.4+5.6j)<class'complex'>SourcePython复数型复数可以分离实数部分和虚数部分复数.real复数.imag复数的共轭复数.conjugate()>>># complex>>> x = 2.4+5.6j>>>x.imag5.6>>>x.real2.4>>>x.conjugate()(2.4-5.6j)SourcePython2.3.2序列类型Pythonrange对象序列类型01字符串02列表03元组单引号、双引号、三引号内的都是字符串,不可变类型强大的类型,用方括号[]界别,可变类型与列表相似,用小括号()界别,不可变类型序列类型是一种容器通过索引访问成员04用range()函数生成一个不可变的数字序列,不可变类型Python字符串的表示单引号双引号三引号>>>myString='HelloWorld!'>>>print(myString)Hello World!>>>myString="Hello World!">>>print(myString)Hello World!>>>myString='''Hello World!'''>>>print(myString)Hello World!Source字符串中字符的访问利用索引值访问单个字符外利用切片操作进行多个字符的访问>>>myString='HelloWorld!'>>>myString[1]'e'>>>myString[1:4]'ell'SourcePython列表可以存储不同类型的数据对象列表中的元素值是可变的>>>aList= [1,'Maths', 88]>>>aList[1, 'Maths', 88]>>>aList[2] =90>>>aList[1, 'Maths', 90]SourcePython元组可以存储不同类型的数据对象元组中的元素值是不可变的>>>aTuple= (1,'Maths', 88)>>>aTuple(1, 'Maths', 88)>>>aTuple[2] = 90Traceback(most recent call last):File "<pyshell#2>", line 1, in <module>aTuple[2] = 90TypeError: 'tuple' object does not support item assignmentSourcePythonrange对象使用range()函数生成一个不可变的数字序列range()函数常常用在for循环中>>>list(range(1, 11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]SourcePython2.3.3字典Python映射类型 字典用大括号{}界别字典每一个元素键值对不可变对象作为键值可以是任意类型>>># dictionary>>> d ={'sine':'sin','cosine':'cos','PI':3.14159}>>> d['sine']'sin'Source字典类型是一种容器通过键访问值PythonPython基本运算2.4PythonPython基本运算ABCD算术运算位运算关系运算逻辑运算>>>and+Python2.4.1算术运算Python算术运算算术运算符的优先级:**>+-(正负号)>* ///%>+ ->>># arithmetic>>> pi = 3.14159>>> r = 3>>>circum= 2 * pi *rSource>>># arithmetic>>>x = 1>>> y = 2>>> z = 3>>> result1 = x + 3/y -z % 2>>> result2 = (x + y**z*4)//5>>>print(circum, result1,result2)18.849541.56SourcePython算术运算中的除法除法有2种运算符“/”和“//”>>>#arithmetic>>> 3 / 40.75>>> 4 / 22.0>>> 5 // 22>>> 3 // 40>>> -6 // 4-2SourcePython2.4.2位运算位运算只适用于整数,位运算就是按整数的二进制位进行的运算>>>~1-2>>> 16 << 264>>> 16 >> 24>>> 64 & 150>>> 64 | 1579>>> 64 ^ 1478Source取反~与&或|异或^左移<<右移>>Python2.4.3关系运算Python关系运算数值的比较:按值比大小字符串的比较:按ASCII码值大小>>># compare>>> 2 == 2True>>> 2.46 <= 8.33True>>>'abc'=='xyz'False>>>'abc'>'xyz'False>>>'abc' < 'xyz'TrueSource小于<大于>小于等于<=大于等于>=等于==不等于!=Python关系运算>>># compare>>> 3 < 4 < 7# same as ( 3 < 4 ) and ( 4 < 7 )True>>> 4 > 3 == 3# same as ( 4 > 3 ) and ( 3 == 3 )True>>> 4 < 3 < 5 != 2 < 7FalseSourcePython2.4.4逻辑运算Python逻辑运算逻辑运算符优先级:not、and、or>>># logical>>> x, y = 3.1415926536, -1024>>> x < 5.0True>>>not(x < 5.0)False>>>not(xisy)TrueSourcePython逻辑运算逻辑运算符优先级:not、and、or>>># logical>>> x, y = 3.1415926536, -1024>>> (x < 5.0)or(y > 2.718281828)True>>> (x < 5.0)and(y > 2.718281828)False>>> 3 < 4 < 7TrueSourcePython2.4.5优先级PythonPython运算符算术运算符>位运算符>关系运算符>逻辑运算符算术运算符的优先级**>+-(正负号)>* / // %>+ -逻辑运算符的优先级not>and>or~Python综合运算>>># mix>>>3 < 2and2 < 1or5 > 4True>>> x, y, z = 1, 2, 3>>> x + 3/y -z % 2> 2False>>>3-2 << 12Source逻辑运算符4关系运算符3算术运算符1位运算符2PythonPython的函数、模块和包2.5Python2.5.1函数PythonPython中的函数内建函数01第三方库03标准库函数02用户自定义函数04Python函数函数可以看成类似于数学中的函数完成一个特定功能的一段代码绝对值函数abs(x)类型函数type(x)“四舍五入”函数round(x)Python内建函数Built-in Functionsabs()dict()help()min()setattr()all()dir()hex()next()slice()any()divmod()id()object()sorted()ascii()enumerate()input()oct()staticmethod()bin()eval()int()open()str()bool()exec()isinstance()ord()sum()bytearray()filter()issubclass()pow()super()bytes()float()iter()print()tuple()callable()format()len()property()type()chr()frozenset()list()range()vars()classmethod()getattr()locals()repr()zip()compile()globals()map()reversed()__import__()complex()hasattr()max()round() delattr()hash()memoryview()set() >>> dir(__builtins__)Python内建函数内建函数str()和type()等适用于所有标准类型数值型内建函数实用函数abs()bool()oct()round()int()hex()divmod()ord()pow()float()chr()complex()dir()input()help()open()len()range()Python内建函数>>># round-offint>>>int(35.4)35>>>int(35.5)35>>>int(35.8)35>>>type(int(35.8))<class 'int'>Source>>>#ord>>>ord('3')51>>>ord('a')97>>>ord('\n')10>>>type(ord('A'))<class 'int'>SourcePython
A
标准库函数:需要先导入模块再使用函数,每个库有相关的一些函数如math库中的sqrt()函数
B
第三方库函数:数量非常惊人,这也是Python重要的特征和优势,例如著名的科学计算包SciPy中就包含了很多用于科学计算的函数
C
用户自定义函数:有固定的定义、调用和参数传递方式等
其他方式定义的函数
Python
库(library)库是一组具有相关功能的模块的集合Python的一大特色就是具有强大的标准库、以及第三方库、以及自定义模块operatormathcmathdecimalrandomarray数值型相关标准库Python2.5.2模块Python模块(一)非内建函数如何使用?>>># round-off floor>>>frommathimport*>>> floor(-35.4)-36>>> floor(-35.5)-36>>> floor(-35.8)-36Source>>># round-off floor>>> floor(5.4)Traceback(most recent call last):File "<pyshell#0>", line 1, in <module>floor(5.4)NameError: name 'floor' is not definedSourcePython模块(二)一个完整的Python文件即是一个模块文件:物理上的组织方式math.py模块:逻辑上的组织方式mathPython通常用“import模块”的方式将现成模块中的函数、类等重用到其他代码块中math.pi的值可以直接使用,不需要自行定义>>>importmath>>>math.pi3.141592653589793SourcePython模块(三)导入多个模块模块里导入指定的模块属性,也就是把指定名称导入到当前作用域>>>importModuleName>>>importModuleName1, ModuleName2, …>>>fromModule1importModuleElement>>>importmath>>> math.log(math.e)1.0>>>math.sqrt(9)3.0>>>frommathimportfloor>>> floor(5.4)5SourcePython2.5.3包Python包(package)一个有层次的文件目录结构定义了一个由模块和子包组成的Python应用程序执行环境A/__init__.pyb.pyC/__init__.pyc1.pyc2.pyD/__init__.pyd1.pyd2.py…>>>importA.C.c1>>>A.C.c1.func1(123)>>>fromA.C.c1importfunc1>>>func1(123)Python小结Python程序基本构成与风格Python语法基础Python数据类型Python基本运算Python中的模块和函数PythonPython
展开更多......
收起↑