资源简介 (共89张PPT)第2章 Python基础Chap2 Python BasicThere is a road in the mountains of books, and diligence is the pathpython程序基本构成与风格2.122.1.1 python程序基本构成3一个小程序4# 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行for number in num: # 第4行prog = prog * number # 第5行print('The prog is: ', prog) # 第6行File程序基本要素变量01表达式02语句03Python输入:input()函数>>> price = input('input the stock price of Apple: ')input the stock price of Apple: 109>>> price'109'>>> type(price)>>> price = int(input('input the stock price of Apple: '))>>> price = eval(input('input the stock price of Apple: '))Source6input()返回的类型是字符型Python输出: print函数Python使用print函数实现输出:print(变量)print(字符串)>>> myString = 'Hello, World!'>>> print(myString)Hello, World!Source72.1.2 python程序设计风格8Python 风格(一)>>> # For loop on a list # 第1行>>> print('The prog is: ', prog) # 第6行Source注释#9Python 风格(二)缩进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: "))for number in num:prog = prog * numberprint("The prog is: ", prog)Source10Python 风格(二)缩进# prog2-1.py# For loop on a list # 第1行num = [1, 2, 3, 4, 5]prog = int(input("please input the value of prog: "))for number in num:prog = prog * numberprint('The prog is: ', prog)Source11Python 风格(三)>>> # 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续行\12Python 风格(三)无需续行符可直接换行的两种情况:小括号、中括号、花括号的内部可以多行书写三引号包括下的字符串也可以跨行书写>>> # triple quotes>>> print('''Hi everybody,welcome to Python’s MOOC course.Here we can learn something aboutPython. Good luck!''')Source续行\13Python 风格(四)>>> 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一行多语句;14python语法基础2.2152.2.1 变量16变量变量引用对象名标识对象>>> # variable>>> PI = 3.14159>>> pi = 'circumference ratio'>>> print(PI)3.14159>>> print(pi)circumference ratioSource17标识符标识符是指Python语言中允许作为变量名或其他对象名称的有效符号首字符是字母或下划线其余可以是字母、下划线、数字大小写敏感(PI和pi是不同的标识符)>>> # Identifier>>> PI = 3.14159>>> pi = 'circumference ratio'>>> print(PI)3.14159>>> print(pi)circumference ratioSource18特殊意义标识符_cat__fish__dog__一个下划线或两个下划线开头的标识符对解释器来讲是有特殊意义,避免使用这种形式的标识符用作一般的变量名。关键字关键字是Python语言的关键组成部分,不可随便作为其他对象的标识符在一门语言中关键字是基本固定的集合在 IDE 中常以不同颜色字体出现20>>> import keyword>>> print(keyword.kwlist)False None True and as assert break class continuedef del elif else except finally for from globalif import in is lambda nonlocal not or passraise return try while with yield关键字21>>> i = 0>>> while i < 20:if i % 2 == 0:print(i)i = i + 1Sourcewhile 和 if在IDLE中显示为橙色,它们均是关键字变量名22>>> num = 5>>> salary = 3450.7>>> tax = salary * 5 * 0.15Source变量命名要见名识义num表示人数salary表示薪酬tax表示税额变量的使用23不同于C语言不需要显式声明变量变量类型不需要专门声明第一次对变量名赋值时自动声明该变量变量的使用24>>> aTraceback (most recent call last):File "", line 1, in aNameError: name 'a' is not defined>>> b = 3.14>>> b3.14>>> c = 'Circle'>>> c'Circle'Source变量必须创建和赋值后使用a没有赋值,所以无法直接使用;变量b和c均有赋值;通过赋值号“=”右边的表达式的结果确定左边变量的类型。变量的使用变量第一次赋值,同时获得类型和“值”Python是动态的强类型语言不需要显式声明,根据“值”确定类型以“引用”的方式实现赋值>>> # Identifier>>> PI = 3.14159>>> pi = 'one word'>>> print(PI)3.14159>>> print(pi)one wordSource=3.14159'one word'piPI25变量的管理26动态类型引用计数a = c,指向了相同的数据对象b和a创建的是不同的5.8对象单独id(5.8)是创建的全新的对象5.85.85.8acb变量的管理27动态类型>>> a = 5.8>>> id(a)1709988157600>>> b = 5.8>>> id(b)1709988157648Source>>> id(5.8)1709988157696>>> c = a>>> id(c)1709988157600>>> c = 3Source变量的管理>>> p = 3>>> q = 3>>> p is qTrueSource3.14159PIpi28>>> PI = 3.14159>>> pi = 3.14159>>> PI is piFalse>>> pi = PI>>> print(PI)3.14159>>> pi is PITrueSourceis运算符的基础是id()函数图中的形式用哪个语句可以表示?2.2.2 表达式和赋值表达式29表达式用运算符连接各种类型数据的式子就是表达式30算术运算符乘方 **正负号 + -乘除 * /整除 //取余 %加减 + -位运算符取反 ~与 &或 |异或 ^左移 <<右移 >>关系运算符小于 <大于 >小于等于 <=大于等于 >=等于 ==不等于 !=逻辑运算符非 not与 and或 or表达式运算符有优先级顺序表达式必须有运算结果>>> # expression>>> PI = 3.14159>>> r = 2>>> c_circ = 2 * PI * r>>> print("The circle's circum is", c_circ)Source2*PI*r 是表达式运算结果赋值给变量 c_circ31赋值 增量赋值>>> # Augmented assignment>>> m = 18>>> m /= 5>>> m3.6Source增量赋值操作符m /=5即 m = m / 532+= -= *= /= %= **=<<= >>= &= ^= |=赋值 链式赋值>>> # Chained assignment>>> a = 1>>> b = a = a + 1>>> b2>>> a2Source33b = a = a + 1相当于如下2条语句:>>> a = a + 1>>> b = a赋值 多重赋值等号左右两边都以元组的方式出现>>> # Multiple assignment>>> PI, r = 3.1415, 3>>> PI3.1415>>> r3Source34相当于:>>> (PI, r) = (3.14159, 3)2.2.3 语句35语句完整执行一个任务的一行逻辑代码赋值语句完成了赋值print()函数调用语句完成了输出>>> # statement>>> PI = 3.14159>>> print(PI)Source36语句和表达式完成一个任务如,打印一份文件语句任务中的一个具体组成部分如,这份文件的具体内容表达式37python数据类型2.338数据类型必须有明确的数据类型,程序才能给对象分配存储空间,从而进行运算0 0 0 0 1 0 0 01 0 0 1 0 0 1 11 0 0 1 0 0 1 11 0 0 1 0 0 1 10 0 0 0 1 0 0 01 0 0 1 1 0 1 139Python数据类型浮点型元组字符串列表字典复数型布尔型(长)整型402.3.1 基本类型41基本类型01(长)整型02布尔型03浮点型4204复数型整型整型和长整型并不严格区分Python 2支持整型值后加“L”即为长整型43>>> # integer>>> type(3)Source布尔型整型的子类仅有2个值:True、False本质上是用整型的1、0分别存储的>>> # boolean>>> x = True>>> type(x)>>> int(x)1>>> y = False>>> int(y)0Source44浮点型即数学中的实数可以类似科学计数法表示>>> # float>>> 3.223.22>>> 9.8e39800.0>>> -4.78e-2-0.0478>>> type(-4.78e-2)Source45复数型 >>> # complex>>> 3j3j>>> type(3j)>>> 5+0j(5+0j)>>> type(5+0j)Source46>>> # complex>>> 2.4+5.6j(2.4+5.6j)>>> type(2.4+5.6j)Source复数型复数可以分离实数部分和虚数部分复数.real复数.imag复数的共轭复数.conjugate()>>> # complex>>> x = 2.4+5.6j>>> x.imag5.6>>> x.real2.4>>> x.conjugate()(2.4-5.6j)Source472.3.2 序列类型48range对象序列类型01字符串02列表03元组单引号、双引号、三引号内的都是字符串,不可变类型强大的类型,用方括号 [] 界别,可变类型与列表相似,用小括号 () 界别,不可变类型49序列类型是一种容器通过索引访问成员04用range()函数生成一个不可变的数字序列,不可变类型字符串的表示单引号双引号三引号>>> myString = 'Hello World!'>>> print(myString)Hello World!>>> myString = "Hello World!">>> print(myString)Hello World!>>> myString = '''Hello World!'''>>> print(myString)Hello World!Source50字符串中字符的访问利用索引值访问单个字符外利用切片操作进行多个字符的访问51>>> myString = 'Hello World!'>>> myString[1]'e'>>> myString[1:4]'ell'Source列表可以存储不同类型的数据对象列表中的元素值是可变的52>>> aList = [1, 'Maths', 88]>>> aList[1, 'Maths', 88]>>> aList[2] = 90>>> aList[1, 'Maths', 90]Source元组可以存储不同类型的数据对象元组中的元素值是不可变的53>>> aTuple = (1, 'Maths', 88)>>> aTuple(1, 'Maths', 88)>>> aTuple[2] = 90Traceback (most recent call last):File "", line 1, in aTuple[2] = 90TypeError: 'tuple' object does not support item assignmentSourcerange对象使用range()函数生成一个不可变的数字序列range()函数常常用在for循环中54>>> list(range(1, 11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Source2.3.3 字典55映射类型 字典用大括号 {} 界别字典每一个元素键值对不可变对象作为键值可以是任意类型>>> # dictionary>>> d ={'sine':'sin','cosine':'cos','PI':3.14159}>>> d['sine']'sin'Source56字典类型是一种容器通过键访问值python基本运算2.457Python基本运算58ABCD算术运算位运算关系运算逻辑运算>>>and+2.4.1 算术运算59算术运算算术运算符的优先级:** >+ -(正负号)>* / // %>+ ->>> # arithmetic>>> pi = 3.14159>>> r = 3>>> circum = 2 * pi * rSource60>>> # arithmetic>>> x = 1>>> y = 2>>> z = 3>>> result1 = x + 3/y -z % 2>>> result2 = (x + y**z*4)//5>>> print(circum, result1, result2)18.84954 1.5 6Source算术运算中的除法除法有2种运算符“/”和“//”61>>> # arithmetic>>> 3 / 40.75>>> 4 / 22.0>>> 5 // 22>>> 3 // 40>>> -6 // 4-2Source2.4.2 位运算62位运算只适用于整数,位运算就是按整数的二进制位进行的运算63>>> ~1-2>>> 16 << 264>>> 16 >> 24>>> 64 & 150>>> 64 | 1579>>> 64 ^ 1478Source取反 ~与 &或 |异或 ^左移 <<右移 >>2.4.3 关系运算64关系运算数值的比较:按值比大小字符串的比较:按ASCII码值大小>>> # compare>>> 2 == 2True>>> 2.46 <= 8.33True>>> 'abc' == 'xyz'False>>> 'abc' > 'xyz'False>>> 'abc' < 'xyz'TrueSource65小于 <大于 >小于等于 <=大于等于 >=等于 ==不等于 !=关系运算>>> # 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 < 7FalseSource662.4.4 逻辑运算67逻辑运算逻辑运算符优先级:not、and、or>>> # logical>>> x, y = 3.1415926536, -1024>>> x < 5.0True>>> not (x < 5.0)False>>> not (x is y)TrueSource68逻辑运算逻辑运算符优先级:not、and、or69>>> # logical>>> x, y = 3.1415926536, -1024>>> (x < 5.0) or (y > 2.718281828)True>>> (x < 5.0) and (y > 2.718281828)False>>> 3 < 4 < 7TrueSource2.4.5 优先级70Python运算符算术运算符 > 位运算符 > 关系运算符 > 逻辑运算符算术运算符的优先级** > + -(正负号)> * / // % > + -逻辑运算符的优先级not > and > or71~综合运算>>> # mix>>> 3 < 2 and 2 < 1 or 5 > 4True>>> x, y, z = 1, 2, 3>>> x + 3/y -z % 2 > 2False>>> 3-2 << 12Source逻辑运算符4关系运算符3算术运算符1位运算符272python的函数、模块和包2.5732.5.1 函数74Python中的函数75内建函数01第三方库03标准库函数02用户自定义函数04函数函数可以看成类似于数学中的函数完成一个特定功能的一段代码绝对值函数abs(x)类型函数type(x)“四舍五入”函数round(x)76内建函数77Built-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__)内建函数内建函数str() 和 type()等适用于所有标准类型数值型内建函数 实用函数abs() bool() oct()round() int() hex()divmod() ord() pow()float() chr() complex()dir() input()help() open()len() range()78内建函数>>> # round-off int>>> int(35.4)35>>> int(35.5)35>>> int(35.8)35>>> type(int(35.8))Source79>>> # ord>>> ord('3')51>>> ord('a')97>>> ord('\n')10>>> type(ord('A'))SourceA标准库函数:需要先导入模块再使用函数,每个库有相关的一些函数如math库中的sqrt()函数B第三方库函数:数量非常惊人,这也是Python重要的特征和优势,例如著名的科学计算包SciPy中就包含了很多用于科学计算的函数C用户自定义函数:有固定的定义、调用和参数传递方式等其他方式定义的函数库(library)库是一组具有相关功能的模块的集合Python的一大特色就是具有强大的标准库、以及第三方库、以及自定义模块81operatormathcmathdecimalrandomarray数值型相关标准库2.5.2 模块82模块(一)非内建函数如何使用?>>> # round-off floor>>> from math import *>>> floor(-35.4)-36>>> floor(-35.5)-36>>> floor(-35.8)-36Source>>> # round-off floor>>> floor(5.4)Traceback (most recent call last):File "", line 1, in floor(5.4)NameError: name 'floor' is not definedSource83模块(二)一个完整的Python文件即是一个模块文件:物理上的组织方式 math.py模块:逻辑上的组织方式 mathPython通常用“import 模块”的方式将现成模块中的函数、类等重用到其他代码块中math.pi的值可以直接使用,不需要自行定义>>> import math>>> math.pi3.141592653589793Source84模块(三)导入多个模块模块里导入指定的模块属性,也就是把指定名称导入到当前作用域85>>>import ModuleName>>>import ModuleName1, ModuleName2, …>>>from Module1 import ModuleElement>>> import math>>> math.log(math.e)1.0>>> math.sqrt(9)3.0>>> from math import floor>>> floor(5.4)5Source2.5.3 包86包(package)一个有层次的文件目录结构定义了一个由模块和子包组成的 Python 应用程序执行环境87A/__init__.pyb.pyC/__init__.pyc1.pyc2.pyD/__init__.pyd1.pyd2.py…>>> import>>> A.C.c1.func1(123)>>> from A.C.c1 import func1>>> func1(123)小结Python程序基本构成与风格Python语法基础Python数据类型Python基本运算Python中的模块和函数8889 展开更多...... 收起↑ 资源预览