0% found this document useful (0 votes)
17 views

(2 1 1) - 第二周Python面面观课件

This document provides an overview of Python and discusses various Python concepts like conditions, loops, and functions. It explains if, else, elif statements and nested conditions. It also covers range(), while, for loops and uses examples to demonstrate break, continue and else clauses in loops. Various examples like calculating square area, guessing games are presented to illustrate different Python programming concepts.

Uploaded by

Pandeng Li
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

(2 1 1) - 第二周Python面面观课件

This document provides an overview of Python and discusses various Python concepts like conditions, loops, and functions. It explains if, else, elif statements and nested conditions. It also covers range(), while, for loops and uses examples to demonstrate break, continue and else clauses in loops. Various examples like calculating square area, guessing games are presented to illustrate different Python programming concepts.

Uploaded by

Pandeng Li
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Multi-dimensional View of 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

if expression : 条件表达式: • expression 条 件 为

expr_true_suite • 比较运算符 True时执行的代码块


• 成员运算符 • 代码块必须缩进(通
• 逻辑运算符 常为4个空格)

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

k = input('input the index of shape: ') O utput

if k == '1': input the index of shape: 3


print('circle') rectangle
elif k == '2':
print('oval')
elif k == '3':
print('rectangle') Input 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

0~300间的整数,玩 # Filename: guessnum1.py


from random import randint
家竞猜,系统给出
x = randint(0, 300)
“猜中”、“太 digit = int(input('Please input a number between 0~300: '))
if digit == x :
大了”或“太小了” print('Bingo!')
的提示。 elif digit > x:
print('Too large, please try again.')
else:
print('Too small, please try again.')

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

异同 range() xrange() 异同 range()

语法 基本一致 语法 与Python 2.x中类似

返回 列表 生成器(类似) 返回 生成器(类似)

生成 真实列表 用多少生成多少 生成 用多少生成多少

Python 2.x Python 3.x

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

语法 可以明确循环的次数

for iter_var in iterable_object: • 遍历一个数据集内的成员


• 在列表解析中使用
suite_to_repeat
• 生成器表达式中使用

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

间的整数, 玩家竞猜, # Filename: guessnum2.py


允许猜多次,系统给出 from random import randint
“猜中”、“太大了”或
x = randint(0, 300)
太 小了”的提示。 for count in range(5):
digit = int(input('Please input a number between 0~300: '))
if digit == x :
print('Bingo!')
elif digit > x:
print('Too large, please try again.')
else:
print('Too small, please try again.')

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

# Filename: breakpro.py # Filename: continuepro.py


sumA = 0 sumA = 0
i=1 i=1
while i <= 5: while i <= 5:
sumA += i sumA += i
if i == 3: i += 1
break if i == 3:
print('i={},sum={}'.format(i, sumA)) continue
i += 1 print('i={},sum={}'.format(i, sumA))

Nanjing University
猜数字游戏(想停就停,非固定次数) 23

• 程序随机产生一个0~300间的整数, F ile

玩家竞猜,允许玩家自己控制游戏 # Filename: guessnum3.py


from random import randint
次数,如果猜中系统给出提示并退 x = randint(0, 300)
go = 'y'
出程序,如果猜错给出“太大了” while go == 'y':
digit = int(input('Please input a number between 0~300: '))
if digit == x :
或“太小了”的提示,如果不想继 print('Bingo!')
break
续玩可以退出并说再见。 elif digit > x:
print('Too large, please try again.')
else:
print('Too small, please try again.')
print('Input y if you want to continue.')
go = input()
else:
print('Goodbye!')

Nanjing University
循环中的else语句 24

• 循环中的else: F ile

– 如果循环代码从 # Filename: prime.py


from math import sqrt
break处终止,跳 num = int(input('Please enter a number: '))
j=2
while j <= int(sqrt(num)):
出循环 if num % j == 0:
print('{:d} is not a prime.'.format(num))
break
– 正常结束循环,则 j += 1
else:
执行else中代码 print('{:d} is a prime.'.format(num))

Nanjing University
25

用Python玩转数据

自定义函数

Nanjing University
函数 26

自定
内置
函数调用之前必须先定义 义
函数
函数

Nanjing University
自定义函数的创建 27

语法

def function_name([arguments]):
"optional documentation string"
function_suite
S ource

>>> def addMe2Me(x):


'apply operation + to argument'
return x+x

Nanjing University
自定义函数的调用 28

• 函数名加上函数运算符, 一对小括号
– 括号之间是所有可选的参数
– 即使没有参数, 小括号也不能省略
Source

S ource >>> addMe2Me(3.7)


7.4
>>> addMe2Me() >>> addMe2Me(5)
Traceback (most recent call last): 10
File "<pyshell#6>", line 1, in <module> >>> addMe2Me('Python')
addMe2Me() 'PythonPython'
TypeError: addMe2Me() takes exactly 1 argument (0 given)

Nanjing University
自定义函数 29

F ile

• 输出1-100之间的 # Filename: prime.py


from math import sqrt
素数 def isprime(x):
if x == 1:
return False
Output: k = int(sqrt(x))
2 3 5 7 11 13 17 19 for j in range(2,k+1):
23 29 31 37 41 43 if x%j == 0:
47 53 59 61 67 71 return False
73 79 83 89 97 return True
for i in range(2,101):
if isprime(i):
print( i, end = ' ')

Nanjing University
默认参数(一) 30

• 函数的参数可以有一个默认值, 如果提供有默认值,在函数定义中,默认参
数以赋值语句的形式提供
S ource

>>> def f(x = True):


'''whether x is a correct word or not'''
if x:
print('x is a correct word')
print('OK')
>>> f()
x is a correct word
OK
>>> f(False)
OK
Nanjing University
默认参数(二) 31

S
• 默认参数的值可以改
ource

>>> def f(x , y = True):


变 '''x and y both correct words or not '''
if y:
print(x, 'and y both correct')
print(x, 'is OK')
>>> f (68)
68 and y both correct
68 is OK
>>> f(68, False)
68 is OK

Nanjing University
默认参数(三) 32

• 默认参数一般需要放置在参数列表的最后

S ource

def f(y = True, x):


'''x and y both correct words or not '''
if y:
print(x, 'and y both correct ')
print(x, 'is OK')

SyntaxError: non-default argument follows default argument

Nanjing University
关键字参数 33

S ource

• 关键字参数是让调用 >>> def f(x , y):


'''x and y both correct words or not '''
者通过使用参数名区 if y:
print(x, 'and y both correct ')
分参数。允许改变参 print(x, 'is OK')
>>> f(68, False)
数列表中的参数顺序 68 is OK
>>> f(y = False, x = 68)
68 is OK
>>> f(y = False, 68)
SyntaxError: non-keyword arg after keyword arg
>>> f(x = 68, False)
SyntaxError: non-keyword arg after keyword arg

Nanjing University
传递函数 34

• 函数可以像参数一样传递给另外一个函数

S ource

>>> def addMe2Me(x):


return x+x
>>> def self(f, y):
print(f(y))
>>> self(addMe2Me, 2.2)
4.4

Nanjing University
lambda函数 35

• 匿名函数

S ource

>>> def addMe2Me(x): S ource

'apply operation + to argument'


return x + x >>> r = lambda x : x + x
>>> addMe2Me(5) >>> r(5)
10 10

Nanjing University
lambda函数 36

def my_add(x, y) : return x + y

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

# the nth Fibonacci number


def fib(n): # the nth Fibonacci number
a, b = 0, 1 def fib(n):
count = 1 if n == 0 or n == 1:
while count < n: return n
a, b = b, a+b
count = count + 1 else:
print(b) return fib(n – 1) + fib(n – 2)

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

You might also like