(2 1 1) - 第二周Python面面观课件
(2 1 1) - 第二周Python面面观课件
Python面面 观
Dazhuang@NJU
Department of Computer Science and Technology
Department of University Basic Computer Teaching
2
用Python玩转数据
条件
Nanjing University
if 语句 3
语法 expression expr_true_suite
F ile
# Filename: ifpro.py
sd1 = 3
sd2 = 3
if sd1 == sd2:
print("the square's area is", sd1*sd2)
Nanjing University
else 语句 4
语法
F ile
if expression :
# Filename: elsepro.py
expr_true_suite sd1 = int(input("the first side: "))
else:
sd2 = int(input("the second side: "))
if sd1 == sd2:
expr_false_suite print("the square's area is", sd1*sd2)
expr_false_suite else:
print("the rectangle's area is", sd1*sd2)
• expression 条 件 为
False 时 执 行 的 代 码
Input and O
utput
块
the first side: 4
• 代码块必须缩进 the second side: 4
• else语句不缩进 the square's area is 16
Nanjing University
elif 语句 5
语法 expr2_true_suite
if expression : • expression2为True时
expr_true_suite 执行的代码块
elif expression2: exprN_true_suite
expr2_true_suite
• expressionN 为 True
:
时执行的代码块
:
elif expressionN : else
exprN_true_suite • none_of_the_above_s
else: uite是以上所有条件都
none_of_the_above_suite 不满足时执行的代码块
Nanjing University
elif 语句 6
F ile
# Filename: elifpro.py I
nput and
elif k == '4':
O utput
print('triangle') input the index of shape: 8
else: you input the invalid number
print('you input the invalid number')
Nanjing University
条件嵌套 7
• 同等缩进为同一条件结构 F ile
# Filename: ifnestpro.py
Input and k = input('input the index of shape: ')
O utput
if k == '1':
print('circle')
input the index of shape: 3 elif k == '2':
the first side: 3 print('oval')
the second side: 4 elif k == '3':
sd1 = int(input('the first side: '))
the rectangle's area is 12 sd2 = int(input('the second side : '))
if sd1 == sd2:
print('the square's area is', sd1*sd2)
Input and else:
print('the rectangle's area is', sd1*sd2)
O utput
elif k == '4':
input the index of shape: 2 print('triangle')
oval else:
print('you input the invalid number')
Nanjing University
猜数字游戏 8
• 程序随机产生一个 F ile
Nanjing University
9
用Python玩转数据
RANGE函数
Nanjing University
range() 10
语法 start
• 起始值(包含)
range (start, end, step=1)
range (start, end) end
range (end) • 终值(不包含)
• 产生一系列整数,返回一个range对象 step
• 步长(不能为0)
S ource
range (start, end, step=1)
>>> list(range(3,11,2)) • 不包含end的值
[3, 5, 7, 9] range (start, end)
>>> list(range(3,11))
• 缺省step值为1
[3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(11)) range (end)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] • 缺省了start值为0,step为1
Nanjing University
range() 11
返回 列表 生成器(类似) 返回 生成器(类似)
Nanjing University
12
用Python玩转数据
循环
Nanjing University
while 循环 13
语法
S ource
while expression:
>>> sumA = 0
suite_to_repeat >>> j = 1
expression >>> while j < 10:
sumA += j
• 条件表达式
j += 1
• 当 expression 值 为 True
>>> sumA
时 执 行 suite_to_repeat 45
代码块 >>> j
10
Nanjing University
for 循环(一) 14
语法 可以明确循环的次数
iterable_object
• String
• List
• Tuple
• Dictionary
• File
Nanjing University
for 循环(二) 15
• 字符串就是一个iterable_object S ource
>>> s = 'python'
• range()返回的也是
>>> for c in s:
iterable_object print(c)
p
y
t
h
o
n
>>> for i in range(3,11,2):
print(i, end = ' ')
3579
Nanjing University
猜数字游戏 16
• 程序随机产生一个0~300 F ile
Nanjing University
17
用Python玩转数据
循环中的
BREAK,CONTINUE和ELSE
Nanjing University
break 语句 18
• break语句终止当前循环,转而执行循环之后的语句
F ile
# Filename: breakpro.py
sumA = 0
i=1
while True:
sumA += i Output:
i += 1 i=6, sum=15
if sumA > 10:
break
print('i={},sum={}'.format(i, sumA))
Nanjing University
while 循环和break 19
F
• 输出2-100之间的
ile
# Filename: prime.py
素数 from math import sqrt
j=2
while j <=100:
Output: i=2
2 3 5 7 11 13 17 19 k= sqrt(j)
23 29 31 37 41 43 while i <= k:
if j%i == 0: break
47 53 59 61 67 71 i = i+1
73 79 83 89 97 if i > k:
print(j, end = ' '))
j += 1
Nanjing University
for 循环和break 20
F ile
• 输出2-100之间的素
# Filename: prime.py
数
from math import sqrt
for i in range(2, 101): flag = 1
k = int(sqrt(i))
Output: for j in range(2, k+1):
2 3 5 7 11 13 17 19 if i%j == 0:
23 29 31 37 41 43 flag = 0
47 53 59 61 67 71 break
73 79 83 89 97 if( flag ):
print(i, end = ' ')
Nanjing University
continue 语句 21
• 在while和for循环中,continue语句的作用:
– 停止当前循环,重新进入循环
– while循环则判断循环条件是否满足
– for循环则判断迭代是否已经结束
Nanjing University
continue语句 22
• 循环中的break: • 循环中的continue:
F ile F ile
Nanjing University
猜数字游戏(想停就停,非固定次数) 23
• 程序随机产生一个0~300间的整数, F ile
Nanjing University
循环中的else语句 24
• 循环中的else: F ile
Nanjing University
25
用Python玩转数据
自定义函数
Nanjing University
函数 26
自定
内置
函数调用之前必须先定义 义
函数
函数
Nanjing University
自定义函数的创建 27
语法
def function_name([arguments]):
"optional documentation string"
function_suite
S ource
Nanjing University
自定义函数的调用 28
• 函数名加上函数运算符, 一对小括号
– 括号之间是所有可选的参数
– 即使没有参数, 小括号也不能省略
Source
Nanjing University
自定义函数 29
F ile
Nanjing University
默认参数(一) 30
• 函数的参数可以有一个默认值, 如果提供有默认值,在函数定义中,默认参
数以赋值语句的形式提供
S ource
S
• 默认参数的值可以改
ource
Nanjing University
默认参数(三) 32
• 默认参数一般需要放置在参数列表的最后
S ource
Nanjing University
关键字参数 33
S ource
Nanjing University
传递函数 34
• 函数可以像参数一样传递给另外一个函数
S ource
Nanjing University
lambda函数 35
• 匿名函数
S ource
Nanjing University
lambda函数 36
lambda x, y : x + y
my_add = lambda x, y : x + y
>>> my_add(3, 5)
8
Nanjing University
37
用Python玩转数据
递归
Nanjing University
递归 38
循环 生成斐波那契数列的方法 递归
递归是最能表现计算思维的算法之一
Nanjing University
循环和递归 39
• 递归必须要有边界条件,即停止递归的条件
– n == 0 or n == 1
• 递归的代码更简洁,更符合自然逻辑,更容易理解
S ource
Source
Nanjing University
递归 40
Nanjing University
递归 41
• 递归的执行
01
02
遇到边界条
件停止递归
系统资源消耗
比 循 环 大 03
Nanjing University
汉诺塔 42
Output:
• 汉诺塔游戏 a -> b
F
三个塔座A、B、C上各有
ile
a -> c
一根针,通过C把64个盘子从 # Filename: Hanoi.py b -> c
A针移动到B针上,移动时必 def hanoi(a,b,c,n): a -> b
c -> a
须遵循下列规则: if n==1: c -> b
(1)圆盘可以插入在A、B print(a,'->',c) a -> b
或C塔座的针上 else: a -> c
hanoi(a,c,b,n-1) b -> c
(2)每次只能移动一个圆盘 b -> a
(3)任何时刻都不能将一个 print(a,'->', c) c -> a
较大的圆盘压在较小的圆盘 hanoi(b,a,c,n-1) b -> c
之上 a -> b
hanoi('a','b','c',4) a -> c
b -> c
Nanjing University
43
用Python玩转数据
变量作用域
Nanjing University
变量作用域 44
• 全局变量
• 局部变量
F ile
S ource
# Filename: global.py
global_str = 'hello' >>> foo()
def foo(): 'helloworld'
local_str = 'world'
return global_str + local_str
Nanjing University
同名变量 45
• 全局变量和局部变量用同一个名字
F ile
# Filename: samename.py
a=3
def f( ):
a=5
print(a ** 2)
Nanjing University
改变全局变量的值 46
• 方法是否可行?
F ile
# Filename: scopeofvar.py
def f(x):
print(a)
a=5
UnboundLocalError: local variable 'a'
print(a + x)
referenced before assignment
a=3
f(8)
Nanjing University
global语句 47
• global语句强调全局变量
F ile
# Filename: scopeofvar.py
def f(x): Output:
global a 3
print(a) 13
a=5
5
print(a + x)
a=3
f(8)
print(a)
Nanjing University