Python程序设计教程课件-第二章Python基础 课件(共89张PPT)

资源下载
  1. 二一教育资源

Python程序设计教程课件-第二章Python基础 课件(共89张PPT)

资源简介

(共89张PPT)
第2章 Python基础
Chap2 Python Basic
There is a road in the mountains of books, and diligence is the path
python程序
基本构成与风格
2.1
2
2.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
语句
03
Python输入: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: '))
Source
6
input()
返回的类型是字符型
Python输出: print函数
Python使用print函数实现输出:
print(变量)
print(字符串)
>>> myString = 'Hello, World!'
>>> print(myString)
Hello, World!
Source
7
2.1.2 python程序设计风格
8
Python 风格(一)
>>> # For loop on a list # 第1行
>>> print('The prog is: ', prog) # 第6行
Source
注释
#
9
Python 风格(二)
缩进
03
01
02
增加缩进表示语句块的开始
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 * number
print("The prog is: ", prog)
Source
10
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 * number
print('The prog is: ', prog)
Source
11
Python 风格(三)
>>> # 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
续行
\
12
Python 风格(三)
无需续行符可直接换行的两种情况:
小括号、中括号、花括号的内部可以多行书写
三引号包括下的字符串也可以跨行书写
>>> # triple quotes
>>> print('''Hi everybody,
welcome to Python’s MOOC course.
Here we can learn something about
Python. Good luck!''')
Source
续行
\
13
Python 风格(四)
>>> x = 'Today' ; y = 'is' ; z = 'Thursday' ; print(x, y, z)
Today is Thursday
Source
>>> x = 'Today'
>>> y = 'is'
>>> z = 'Thursday'
>>> print(x, y, z)
Today is Thursday
Source
一行多语句
;
14
python
语法基础
2.2
15
2.2.1 变量
16
变量
变量
引用
对象

标识
对象
>>> # variable
>>> PI = 3.14159
>>> pi = 'circumference ratio'
>>> print(PI)
3.14159
>>> print(pi)
circumference ratio
Source
17
标识符
标识符是指Python语言中允许作为变量名或其他对象名称的有效符号
首字符是字母或下划线
其余可以是字母、下划线、数字
大小写敏感(PI和pi是不同的标识符)
>>> # Identifier
>>> PI = 3.14159
>>> pi = 'circumference ratio'
>>> print(PI)
3.14159
>>> print(pi)
circumference ratio
Source
18
特殊意义标识符
_cat
__fish
__dog__
一个下划线或两个下划线开头的标识符对解释器来讲是有特殊意义,避免使用这种形式的标识符用作一般的变量名。
关键字
关键字是Python语言的关键组成部分,不可随便作为其他对象的标识符
在一门语言中关键字是基本固定的集合
在 IDE 中常以不同颜色字体出现
20
>>> import keyword
>>> print(keyword.kwlist)
False None True and as assert break class continue
def del elif else except finally for from global
if import in is lambda nonlocal not or pass
raise return try while with yield
关键字
21
>>> i = 0
>>> while i < 20:
if i % 2 == 0:
print(i)
i = i + 1
Source
while 和 if在IDLE中显示为橙色,它们均是关键字
变量名
22
>>> num = 5
>>> salary = 3450.7
>>> tax = salary * 5 * 0.15
Source
变量命名要见名识义
num表示人数
salary表示薪酬
tax表示税额
变量的使用
23
不同于C语言
不需要显式声明变量
变量类型不需要专门声明
第一次对变量名赋值时自动声明该变量
变量的使用
24
>>> a
Traceback (most recent call last):
File "", line 1, in
a
NameError: name 'a' is not defined
>>> b = 3.14
>>> b
3.14
>>> c = 'Circle'
>>> c
'Circle'
Source
变量必须创建和赋值后使用
a没有赋值,所以无法直接使用;变量b和c均有赋值;通过赋值号“=”右边的表达式的结果确定左边变量的类型。
变量的使用
变量第一次赋值,同时获得类型和“值”
Python是动态的强类型语言
不需要显式声明,根据“值”确定类型
以“引用”的方式实现赋值
>>> # Identifier
>>> PI = 3.14159
>>> pi = 'one word'
>>> print(PI)
3.14159
>>> print(pi)
one word
Source
=
3.14159
'one word'
pi
PI
25
变量的管理
26
动态类型
引用计数
a = c,指向了相同的数据对象
b和a创建的是不同的5.8对象
单独id(5.8)是创建的全新的对象
5.8
5.8
5.8
a
c
b
变量的管理
27
动态类型
>>> a = 5.8
>>> id(a)
1709988157600
>>> b = 5.8
>>> id(b)
1709988157648
Source
>>> id(5.8)
1709988157696
>>> c = a
>>> id(c)
1709988157600
>>> c = 3
Source
变量的管理
>>> p = 3
>>> q = 3
>>> p is q
True
Source
3.14159
PI
pi
28
>>> PI = 3.14159
>>> pi = 3.14159
>>> PI is pi
False
>>> pi = PI
>>> print(PI)
3.14159
>>> pi is PI
True
Source
is运算符的基础是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)
Source
2*PI*r 是表达式
运算结果赋值给变量 c_circ
31
赋值 增量赋值
>>> # Augmented assignment
>>> m = 18
>>> m /= 5
>>> m
3.6
Source
增量赋值操作符
m /=5
即 m = m / 5
32
+= -= *= /= %= **=
<<= >>= &= ^= |=
赋值 链式赋值
>>> # Chained assignment
>>> a = 1
>>> b = a = a + 1
>>> b
2
>>> a
2
Source
33
b = a = a + 1相当于
如下2条语句:
>>> a = a + 1
>>> b = a
赋值 多重赋值
等号左右两边都以元组的方式出现
>>> # Multiple assignment
>>> PI, r = 3.1415, 3
>>> PI
3.1415
>>> r
3
Source
34
相当于:
>>> (PI, r) = (3.14159, 3)
2.2.3 语句
35
语句
完整执行一个任务的一行逻辑代码
赋值语句完成了赋值
print()函数调用语句完成了输出
>>> # statement
>>> PI = 3.14159
>>> print(PI)
Source
36
语句和表达式
完成一个任务
如,打印一份文件
语句
任务中的一个具体组成部分
如,这份文件
的具体内容
表达式
37
python
数据类型
2.3
38
数据类型
必须有明确的数据类型,程序才能给对象分配存储空间,从而进行运算
0 0 0 0 1 0 0 0
1 0 0 1 0 0 1 1
1 0 0 1 0 0 1 1
1 0 0 1 0 0 1 1
0 0 0 0 1 0 0 0
1 0 0 1 1 0 1 1
39
Python数据类型
浮点型
元组
字符串
列表
字典
复数型
布尔型
(长)整型
40
2.3.1 基本类型
41
基本类型
01
(长)整型
02
布尔型
03
浮点型
42
04
复数型
整型
整型和长整型并不严格区分
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)
0
Source
44
浮点型
即数学中的实数
可以类似科学计数法表示
>>> # float
>>> 3.22
3.22
>>> 9.8e3
9800.0
>>> -4.78e-2
-0.0478
>>> type(-4.78e-2)

Source
45
复数型

>>> # complex
>>> 3j
3j
>>> type(3j)

>>> 5+0j
(5+0j)
>>> type(5+0j)

Source
46
>>> # 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.imag
5.6
>>> x.real
2.4
>>> x.conjugate()
(2.4-5.6j)
Source
47
2.3.2 序列类型
48
range对象
序列类型
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!
Source
50
字符串中字符的访问
利用索引值访问单个字符外
利用切片操作进行多个字符的访问
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] = 90
Traceback (most recent call last):
File "", line 1, in
aTuple[2] = 90
TypeError: 'tuple' object does not support item assignment
Source
range对象
使用range()函数生成一个不可变的数字序列
range()函数常常用在for循环中
54
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Source
2.3.3 字典
55
映射类型 字典
用大括号 {} 界别
字典每一个元素键值对
不可变对象作为键
值可以是任意类型
>>> # dictionary
>>> d ={'sine':'sin','cosine':'cos','PI':3.14159}
>>> d['sine']
'sin'
Source
56
字典类型是一种容器
通过键访问值
python
基本运算
2.4
57
Python基本运算
58
A
B
C
D
算术运算
位运算
关系运算
逻辑运算
>>
>
and
+
2.4.1 算术运算
59
算术运算
算术运算符的优先级:** >+ -(正负号)>* / // %>+ -
>>> # arithmetic
>>> pi = 3.14159
>>> r = 3
>>> circum = 2 * pi * r
Source
60
>>> # 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 6
Source
算术运算中的除法
除法有2种运算符
“/”和“//”
61
>>> # arithmetic
>>> 3 / 4
0.75
>>> 4 / 2
2.0
>>> 5 // 2
2
>>> 3 // 4
0
>>> -6 // 4
-2
Source
2.4.2 位运算
62
位运算
只适用于整数,位运算就是按整数的二进制位进行的运算
63
>>> ~1
-2
>>> 16 << 2
64
>>> 16 >> 2
4
>>> 64 & 15
0
>>> 64 | 15
79
>>> 64 ^ 14
78
Source
取反 ~
与 &
或 |
异或 ^
左移 <<
右移 >>
2.4.3 关系运算
64
关系运算
数值的比较:按值比大小
字符串的比较:按ASCII码值大小
>>> # compare
>>> 2 == 2
True
>>> 2.46 <= 8.33
True
>>> 'abc' == 'xyz'
False
>>> 'abc' > 'xyz'
False
>>> 'abc' < 'xyz'
True
Source
65
小于 <
大于 >
小于等于 <=
大于等于 >=
等于 ==
不等于 !=
关系运算
>>> # 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 < 7
False
Source
66
2.4.4 逻辑运算
67
逻辑运算
逻辑运算符优先级:
not、and、or
>>> # logical
>>> x, y = 3.1415926536, -1024
>>> x < 5.0
True
>>> not (x < 5.0)
False
>>> not (x is y)
True
Source
68
逻辑运算
逻辑运算符优先级:
not、and、or
69
>>> # logical
>>> x, y = 3.1415926536, -1024
>>> (x < 5.0) or (y > 2.718281828)
True
>>> (x < 5.0) and (y > 2.718281828)
False
>>> 3 < 4 < 7
True
Source
2.4.5 优先级
70
Python运算符
算术运算符 > 位运算符 > 关系运算符 > 逻辑运算符
算术运算符的优先级
** > + -(正负号)> * / // % > + -
逻辑运算符的优先级
not > and > or
71
~
综合运算
>>> # mix
>>> 3 < 2 and 2 < 1 or 5 > 4
True
>>> x, y, z = 1, 2, 3
>>> x + 3/y -z % 2 > 2
False
>>> 3-2 << 1
2
Source
逻辑运算符
4
关系运算符
3
算术运算符
1
位运算符
2
72
python的
函数、模块和包
2.5
73
2.5.1 函数
74
Python中的函数
75
内建函数
01
第三方库
03
标准库函数
02
用户自定义函数
04
函数
函数可以看成类似于数学中的函数
完成一个特定功能的一段代码
绝对值函数abs(x)
类型函数type(x)
“四舍五入”函数round(x)
76
内建函数
77
Built-in Functions
abs() 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))

Source
79
>>> # ord
>>> ord('3')
51
>>> ord('a')
97
>>> ord('\n')
10
>>> type(ord('A'))

Source
A
标准库函数:需要先导入模块再使用函数,每个库有相关的一些函数如math库中的sqrt()函数
B
第三方库函数:数量非常惊人,这也是Python重要的特征和优势,例如著名的科学计算包SciPy中就包含了很多用于科学计算的函数
C
用户自定义函数:有固定的定义、调用和参数传递方式等
其他方式定义的函数
库(library)
库是一组具有相关功能的模块的集合
Python的一大特色就是具有强大的标准库、以及第三方库、以及自定义模块
81
operator
math
cmath
decimal
random
array
数值型相关标准库
2.5.2 模块
82
模块(一)
非内建函数如何使用?
>>> # round-off floor
>>> from math import *
>>> floor(-35.4)
-36
>>> floor(-35.5)
-36
>>> floor(-35.8)
-36
Source
>>> # round-off floor
>>> floor(5.4)
Traceback (most recent call last):
File "", line 1, in
floor(5.4)
NameError: name 'floor' is not defined
Source
83
模块(二)
一个完整的Python文件即是一个模块
文件:物理上的组织方式 math.py
模块:逻辑上的组织方式 math
Python通常用“import 模块”的方式将现成模块中的函数、类等重用到其他代码块中
math.pi的值可以直接使用,不需要自行定义
>>> import math
>>> math.pi
3.141592653589793
Source
84
模块(三)
导入多个模块
模块里导入指定的模块属性,也就是把指定名称导入到当前作用域
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)
5
Source
2.5.3 包
86
包(package)
一个有层次的文件目录结构
定义了一个由模块和子包组成的 Python 应用程序执行环境
87
A/
__init__.py
b.py
C/
__init__.py
c1.py
c2.py
D/
__init__.py
d1.py
d2.py

>>> import
>>> A.C.c1.func1(123)
>>> from A.C.c1 import func1
>>> func1(123)
小结
Python程序基本构成与风格
Python语法基础
Python数据类型
Python基本运算
Python中的模块和函数
88
89

展开更多......

收起↑

资源预览