资源简介 (共98张PPT)第5章 程序控制结构Chap5 Program Control StructureThere is a road in the mountains of books, and diligence is the path程序控制结构2顺序选择循环sequencestructureselection structurerepetition structure顺序结构5.13顺序结构4AB# Filename: seq.pymystring = 'Hello, World!' print(mystring)File一个入口一个出口5.1.1 赋值语句5赋值语句6普通赋值r = 2增量赋值m /= 5链式赋值b = a = a + 1多重赋值p , r = 3 , 5多重赋值多重赋值的基本形式7变量1, 变量2, …, 变量n = 表达式1, 表达式2, …, 表达式n>>> name, age = 'Niuyun', 18>>> name'Niuyun'>>> age18Source多重赋值的本质8>>> name, age = 'Niuyun', 18>>> temp = 'Niuyun', 18>>> temp('Niuyun', 18)>>> name, age = temp>>> name'Niuyun'>>> age18Source元组打包Tuple packing序列解包Sequence unpacking多重赋值9>>> x = 3>>> y = 5>>> x, y = y, x>>> x5>>> y3Source语法糖syntactic sugar5.1.2 基本输入和输出语句10输入/输出11输入输出input()print()输入函数input()12输入语句的一般形式:x = input(['输入提示'])返回值类型是str输入input()函数13>>> x = input('Enter an integer between 0 and 10: ')Enter an integer between 0 and 10: 3>>> x'3'>>> x = int(input('Enter an integer between 0 and 10: '))Enter an integer between 0 and 10: 3>>> x3>>> y = float(input('Enter the price of the apples: '))Enter the price of the apples: 4.5>>> y4.5Source返回值类型:strint()函数float()函数输入input()函数14>>> z = eval(input('Enter a number: '))Enter a number: 3>>> z * 39>>> z = eval(input('Enter the price of every apple: '))Enter the price of every apple: 3.5>>> z * 310.5>>> z = eval(input('Enter the price of the apples: '))Enter the price of the apples: 3 * 3.5>>> z10.5Source返回值类型:streval()函数将输入的的字符串当成有效的Python表达式来求值输出函数print()15输出语句的一般形式:print(对象1, 对象2, …, 对象n, sep = ' ', end = '\n' )输出到标准输出设备sep表示输出对象之间的分隔符,默认为空格参数end的默认值为'\n',表示print()函数输出完成后自动换行输出函数print()16>>> print('1', '2', '3')1 2 3>>> print('1', '2', '3', sep = ',')1,2,3Source改变sep的值输出函数print()17格式化输出形式:print('格式字符串' % (对象1, 对象2, …, 对象n))print('格式化'.format(对象1, 对象2, …, 对象n))输出函数print()——格式化18>>> "{0} is taller than {1}.".format("Xiaoma", "Xiaowang")'Xiaoma is taller than Xiaowang.'>>> age, height = 21, 1.758>>> print("Age:{0:<5d}, Height:{1:5.2f}".format(age, height))Age:21 , Height: 1.76Source{参数的位置:[对齐说明符][符号说明符][最小宽度说明符][.精度说明符][类型说明符]}可以认为{0}或{0:<5d}是替换参数的占位符。其中数字表示参数的位置,从0开始编号,:后的<5d为格式说明符。格式说明符的格式如下符号 描述b 二进制,以2为基数输出数字o 八进制,以8为基数输出数字x 十六进制,以16为基数输出数字,9以上的数字用小写字母(类型符为X时用大写字母)表示c 字符,将整数转换成对应的Unicode字符输出d 十进制整数,以10为基数输出数字f 定点数,以定点数输出数字e 指数记法,以科学计数法输出数字,用e(类型符是E时用大写E)表示幂[+]m.nf 输出带符号(若格式说明符中显式使用了符号“+”,则输出大于或等于0的数时带“+”号)的数,保留n位小数,整个输出占m列(若实际宽度超过m则突破m的限制)0>5d 右对齐,>左边的0表示用0填充左边,>右边的数字5表示输出项宽度为5< 左对齐,默认用空格填充右边,<前后类似上述右对齐可以加填充字符和宽度^ 居中对齐{{}} 输出一个{}19格式说明符选择结构5.2205.2.1 条件21if 语句if 表达式(条件) :语句序列语 法简单的数字或字符条件表达式:关系运算符成员运算符逻辑运算符True 或 False表达式(条件)条件为True时执行的代码块同一语句序列必须在同一列上进行相同的缩进(通常为4个空格)语句序列22if 语句# Filename: ifpro.pysd1 = 3sd2 = 3if sd1 == sd2:print("the square's area is", sd1*sd2)File23the square's area is 9Input and Output24例5.1 程序随机产生一个0~300之间的整数,玩家竞猜,若猜中则提示Bingo单分支结构流程图表达式语句序列TrueFalse猜数字流程图x == num输出Bingo!TrueFalse# prog5-1.pyfrom random import randintx = randint(0, 300)num = int(input('Please enter a number between 0~300: '))if num == x:print('Bingo!')File25例5.1 程序随机产生一个0~300之间的整数,玩家竞猜,若猜中则提示Bingo很难一次性猜对!而且毫无反馈!5.2.2 else子句26else 语句27if 表达式:语句序列1else:语句序列2语 法表达式条件为False时执行的代码块代码块必须缩进else语句不缩进语句序列2表达式语句序列1TrueFalse两路分支结构流程图语句序列228例5.2 程序随机产生一个0~300之间的整数,玩家竞猜,若猜中则提示Bingo,否则提示Wrong# prog5-2.pyfrom random import randintx = randint(0, 300)num = int(input('Please enter a number between 0~300: '))if num == x:print('Bingo!')else:print('Wrong!')FilePlease enter a number between 0~300: 178Wrong!Input and Outputelse 语句# Filename: elsepro.pysd1 = int(input('the first side: '))sd2 = int(input('the second side: '))if sd1 == sd2:print("the square's area is", sd1*sd2)else:print("the rectangle's area is", sd1*sd2)File29the first side: 4the second side: 4the square's area is 16Input and Outputelse 语句30# Filename: elsepro-2.pyx = eval(input('Please enter the first number: '))y = eval(input('Please enter the second number: '))if x >= y:t = xelse:t = yFile检查条件“x >= y”是否满足,若满足则取x否则取y赋给变量telse 语句——三元运算符31条件表达式(也称三元运算符)的常见形式如下所述:x if C else y# Filename: elsepro-2.pyx = eval(input('Please enter the first number: '))y = eval(input('Please enter the second number: '))if x >= y:t = xelse:t = yFilet = x if x >= y else y5.2.3 elif子句32elif 语句33if 表达式1:语句序列1elif 表达式2:语句序列2…elif 表达式N-1:语句序列N-1else:语句序列N语 法表达式2为True时执行的代码块语句序列2表达式N为True时执行的代码块语句序列N-1语句序列N是以上所有条件都不满足时执行的代码块语句序列Nelif 语句34多分支结构流程图语句序列2True表达式1语句序列1TrueFalse表达式2False表达式n-1TrueFalseFalse语句序列n-1语句序列n…例5.3 猜数字游戏程序随机产生一个0~300之间的整数,玩家竞猜,若猜中则提示Bingo,若猜大了提示Too large,否则提示Too small# Filename: 5-3-1.pyfrom random import randintx = 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.')File35elif 语句# Filename: elifpro.pyk = input('input the index of shape: ')if k == '1':print('circle')elif k == '2':print('oval')elif k == '3':print('rectangle')elif k == '4':print('triangle')else:print('you input the invalid number')Fileinput the index of shape: 3rectangleInput and Outputinput the index of shape: 8you input the invalid numberInput and Output365.2.4 嵌套的if语句37嵌套的if语句381 : if 表达式1:2 : if 表达式2:3 : 语句序列14 : else:5 : 语句序列26 : else:7 : if 表达式3:8 : 语句序列39 : else:10: 语句序列4语 法条件嵌套同等缩进为同一条件结构# Filename: ifnestpro.pyk = input('input the index of shape: ')if k == '1':print('circle')elif k == '2':print('oval')elif k == '3':sd1 = int(input('the first side: '))sd2 = int(input('the second side : '))if sd1 == sd2:print("the square's area is", sd1*sd2)else:print("the rectangle's area is", sd1*sd2)elif k == '4':print('triangle')else:print('you input the invalid number')Fileinput the index of shape: 3the first side: 3the second side: 4the rectangle's area is 12Input and Outputinput the index of shape: 2ovalInput and Output39例5.3 猜数字游戏——改写代码# Filename: 5-3-1.pyfrom random import randintx = 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.')File40# Filename: 5-3-2.pyfrom random import randintx = randint(0, 300)digit = int(input('Please input a number between 0~300: '))if digit == x :print('Bingo!')else:if digit > x:print('Too large, please try again.')else:print('Too small, please try again.')File例5.4 符号函数(sign function)41请分别用if-elif-else结构和嵌套的if结构实现符号函数(sign function),符号函数的定义: 例5.4 符号函数42# prog5-4-1.pyx = eval(input('Enter a number: '))if x < 0:sgn = -1elif x == 0:sgn = 0else:sgn = 1print ('sgn = {:.0f}'.format(sgn))File# prog5-4-2.pyx = eval(input('Enter a number: '))if x != 0:if x < 0:sgn = -1else:sgn = 1else:sgn = 0print ('sgn = {:.0f}'.format(sgn))File循环结构5.343循环循环结构是满足一个指定的条件,每次使用不同的数据对算法中的计算或处理步骤完全相同的部分重复计算若干次的算法结构,也称为重复结构440103025.3.1 while语句45while 循环46While 表达式:语句序列(循环体)语法当表达式值为True时执行语句序列代码块继续判断表达式的值是否为True,若是则继续执行循环体,如此周而复始,直到表达式的值为False或发生异常时停止循环的执行表达式while 语句47表达式True语句序列Falsewhile语句流程图有几点要注意:while语句是先判断再执行,所以循环体有可能一次也不执行;循环体中需要包含能改变循环变量值的语句,否则表达式的结果始终是True的话会造成死循环;要注意语句序列的对齐,while语句只执行其后的一条或一组同一层次的语句。例5.5 计算1+2+…+100的值# prog5-5.pys = 0i = 1while i <= 100:s += ii += 1print('1+2+…+100 = {:d}'.format(s))Source48input the index of shape: 2ovalInput and Output经典累加问题例5.6 求两个正整数的最大公约数和最小公倍数。49# prog5-6.py# -*- coding: gb2312 -*-x = eval(input("Enter the first number: "))y = eval(input("Enter the second number: "))z = x * yif x < y:x, y = y, xwhile x % y != 0:r = x % yx = yy = rprint("最大公约数 = ", y)print(“最小公倍数 = ", z // y)SourceS1:判断x除以y的余数r是否为0。若r为0则y是x、y的最大公约数,继续执行后续操作;否则y→x,r→y重复执行第S1步。S2:输出(或返回)y。Enter the first number: 18Enter the second number: 24最大公约数 = 6最小公倍数 = 72Input and Output例5.7 计算π50# prog5-7.pyimport mathx, s = 1, 0sign = 1k = 1while math.fabs(x) > 1e-8:s += xk += 2sign *= -1x = sign / ks *= 4print("pi = {:.15f}".format(s))Sourcepi = 3.141592633590251Input and Output math模块中pi值等于5.3.2 for语句51for 循环52for 变量 in 可迭代对象:语句序列语 法遍历一个数据集内的成员在列表解析中使用生成器表达式中使用可以明确循环的次数StringListTupleDictionaryFile可迭代对象for 循环53取可迭代对象中的元素可以取到元素语句序列无元素可取for语句流程图可迭代对象指可以按次序迭代(循环)的对象,包括序列、迭代器(iterator)如enumerate()函数产生的对象以及其他可以迭代的对象如字典的键和文件的行等。执行时变量取可迭代对象中的一个值,执行语句序列,再取下一个值,执行语句序列猜数字游戏54程序随机产生一个0~300间的整数, 玩家竞猜,允许猜多次,系统给出 “猜中”、“太大了”或太 小了”的提示。# Filename: guessnum2.pyfrom random import randintx = 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.')Filefor 循环55# Filename: prog_for.pyfor fruit in ['apple', 'banana', 'pear']:print(fruit)for item in enumerate(['a', 'b', 'c']):print(item)FileapplebananaPear(0, 'a')(1, 'b')(2, 'c')Input and Output迭代器 or 列表?列表,在每次取值时会一次性获取所有值,如果值多的话,会占用更多的内存;而迭代器则是一个接一个计算值,在使用时计算一个值时获取一个值,占内存少。for循环——可迭代对象56序列01序列索引02迭代器03字典的键04文件的行05for 语句迭代——序列迭代>>> s = 'Python'>>> for c in s:print(c)Python>>> for i in range(3,11,2):print(i, end = ' ')3 5 7 9Source57>>> s = ['I', 'love', 'Python']>>> for word in s:print(word, end = ' ')I love Python>>> for i in range(1, 5):print(i * i)14916Sourcefor 语句迭代——序列索引迭代58>>> s = ['I', 'love', 'Python']>>> for i in range(len(s)):print(s[i], end = ' ')I love PythonSourcefor 语句迭代——迭代器迭代59>>> courses = ['Maths', 'English', 'Python']>>> scores = [88, 92, 95]>>> for c, s in zip(courses, scores):print('{0} – {1:d}'.format(c, s))Maths - 88English - 92Python - 95Sourcefor 语句迭代——其他迭代60>>> d_stock = {'AXP': '78.51', 'BA': '184.76', 'CAT': '96.39'}>>> for k, v in d_stock.items():print('{0:>3}: {1}'.format(k, v))AXP: 78.51BA: 184.76CAT: 96.39>>> for k in d_stock.keys():print(k, d_stock[k])AXP 78.51BA 184.76CAT 96.39Source例5.8 求斐波纳契(Fibonacci)数列前20项斐波纳契数列:0,1,1,2,3,5,8,13,21,34,55,89,144,…61 # prog5-8.pyf = [0] * 20f[0], f[1] = 0, 1for i in range(2, 20):f[i] = f[i-1] + f[i-2]print(f)File[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]Input and Output例5.9 输出集体代码和股票价格假设已有若干道琼斯工业指数成分股集体某个时期的财经数据,包括集体代码、集体名称和股票价格:>>> stockList =[('AXP', 'American Express Company', '78.51'),('BA', 'The Boeing Company', '184.76'),('CAT', 'Caterpillar Inc.', '96.39')]从数据中获取集体代码和股票价格对并输出。62例5.9 输出集体代码和股票价格63# prog5-9-1.pystockList =[('AXP', 'American Express Company','78.51'), ('BA', 'The Boeing Company','184.76'), ('CAT', 'Caterpillar Inc.', '96.39')]aList = []bList = []for i in range(3):aStr = stockList[i][0]bStr = stockList[i][2]aList.append(aStr)bList.append(bStr)stockDict = dict(zip(aList,bList))print(stockDict)File{'CAT': '96.39', 'BA': '184.76', 'AXP': '78.51'}Input and Output用序列索引迭代例5.9 输出集体代码和股票价格64# prog5-9-2.pystockList =[('AXP', 'American Express Company','78.51'), ('BA', 'The Boeing Company','184.76'), ('CAT', 'Caterpillar Inc.', '96.39')]stockDict = {}for data in stockList:stockDict[data[0]] = data[2]print(stockDict)File{'CAT': '96.39', 'BA': '184.76', 'AXP': '78.51'}Input and Output用序列迭代5.3.3 嵌套循环65循环嵌套while语句和for语句可以嵌套自身语句结构,也可以相互嵌套,可以呈现各种复杂的形式。66例5.10 编写程序统计一元人民币换成一分、两分和五分的所有兑换方案个数67# prog5-10.pyi, j, k = 0, 0, 0 # i,j,k分别代表五分、两分和一分的数量count = 0for i in range(21):for j in range(51):k = 100 - 5 * i - 2 * jif k >= 0: #k是一分,可以是任意个count += 1print('count = {:d}'.format(count))Filecount = 541Input and Output可以用while替换for例5.11 两个列表的新组合从两个列表中分别选出一个元素,组成一个元组放到一个新列表中,要求新列表中包含所有的组合68# prog5-11.pyresult = []pdlList = ['C++', 'Java', 'Python']creditList = [2, 3, 4]for pdl in pdlList:for credit in creditList:result.append((pdl, credit))print(result)File[('C++', 2), ('C++', 3), ('C++', 4), ('Java', 2), ('Java', 3), ('Java', 4), ('Python', 2), ('Python', 3), ('Python', 4)]Input and Output5.3.4 break, continue语句69break 语句break语句终止当前循环,转而执行循环之后的语句# Filename: breakpro.pys = 0i = 1while i < 10:s += iif s > 10:breaki += 1print('i = {0:d}, sum = {1:d}'.format(i, s))File70s是1+2+3+…不断累加的和,当i等于5时s第一次大于10,执行break语句跳出while循环语句,继而去执行print语句i=5, s=15Input and Output循环非正常结束break 语句“while i < 10:”意义不大,常会将此条语句替换成另一种在Python中常与break语句一起使用的的循环控制语句“while True:”# Filename: breakpro.pys = 0i = 1while True:s += iif s > 10:breaki += 1print('i = {0:d}, sum = {1:d}'.format(i, s))File71while i < 10:while True:break 语句i 和 j 分别等于5和10时 i 和 j 的乘积第一次等于50,如果break语句可以跳出两重循环的话则输出结果应该是“5 10”,而程序的实际输出结果是“10 5”,所以break只能跳出紧包层即break所在层次的循环。for i in range(11):for j in range(11):if i * j >= 50:breakprint(i, j)File72两重循环例5.12 输出2~100之间的素数,每行显示5个素数(prime): 只能被1和n自身整除的正整数n(13是素数,6不是素数)。素数判断算法:若n不能被2~n-1范围内的任一个整数整除n就是素数,否则n不是素数如果发现n能被某个整数整除可立即停止继续判断n是否能被范围内其他整数整除。732 3 5 7 1113 17 19 23 2931 37 41 43 4753 59 61 67 7173 79 83 89 97Input and Output2~n/2 or例5.12 输出2~100之间的素数,每行显示5个# Filename: 5-12.pyfrom math import sqrtj = 2 ; count = 0while j <=100:i = 2k= sqrt(j)while i <= k:if j%i == 0: breaki += 1if i > k:count += 1if count % 5 == 0:print(j, end = '\n')else:print(j, end = ' '))j += 1File742 3 5 7 1113 17 19 23 2931 37 41 43 4753 59 61 67 7173 79 83 89 97Input and Outputfor 循环和breakfor 循环和breakfrom math import sqrtfor i in range(2,101):k = int(sqrt(i)); flag = 1for j in range(2,k+1):if i%j == 0:flag = 0breakif ( flag ):count += 1if count % 5 == 0:print(i, end = '\n')else:print(i, end = ' '))File752 3 5 7 1113 17 19 23 2931 37 41 43 4753 59 61 67 7173 79 83 89 97Input and Outputcontinue 语句在while和for循环中,continue语句的作用:跳过循环体内continue后面的语句,并开始新的一轮循环while循环则判断循环条件是否满足for循环则判断迭代是否已经结束76continue语句77程序的功能是对于在1~20之间的数,当它是3的倍数时执行print(i, end = ' ')函数调用语句,当它不是3的倍数时执行continue语句,跳过其后的print()函数调用语句继续执行下一轮循环for i in range(1,21):if i % 3 != 0:continueprint(i, end = ' ')File3 6 9 12 15 18Input and Outputcontinue语句循环中的break:78循环中的continue:for i in range(1,21):if i % 3 != 0:continueprint(i, end = ' ')Filefor i in range(1,21):if i % 3 != 0:breakprint(i, end = ' ')Filebreak continuebreak语句跳出所有轮循环 continue语句则是跳出本轮循环没有任何输出 输出1-20之间所有3的倍数“3 6 9 12 15 18”continue语句循环中的替代continue:79循环中的continue:for i in range(1,21):if i % 3 != 0:continueprint(i, end = ' ')Filefor i in range(1,21):if i % 3 == 0:print(i, end = ' ')File5.3.5 循环结构中的else子句80循环中的else子句循环中的else子句:如果循环代码从break处终止,跳出循环正常结束循环,则执行else中代码81例5.14 输入一个整数,并判断其是否为素数82# Filename: 5-14.pyfrom math import sqrtnum = int(input('Please enter a number: '))j = 2while j <= int(sqrt(num)):if num % j == 0:print('{:d} is not a prime.'.format(num))breakj += 1else:print('{:d} is a prime.'.format(num))File如果输入的整数有有效因子(除了1和它本身的因子)则可以直接输出非素数的结论并继而执行break语句跳出循环,如果没有执行过break语句则表示循环正常结束,也就是整数并无有效因子则表明它是一个素数,则执行else子句的输出语句。例5.15 猜数字游戏(想停就停,非固定次数)83程序随机产生一个0~300间的整数,玩家竞猜,允许玩家自己控制游戏次数,如果猜中系统给出提示并退出程序,如果猜错给出“太大了”或“太小了”的提示,如果不想继续玩可以退出并说再见。# Filename: guessnum3.pyfrom random import randintx = randint(0, 300)go = 'y'while (go == 'y'):digit = int(input('Please input a number between 0~300: '))if digit == x :print('Bingo!')breakelif 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()print(go)else:print('I quit and byebye!')File5.3.6 特殊的循环—列表解析84列表解析Python中有一种特殊的循环,通过for语句结合if语句,利用其他列表动态生成新列表,这种特殊的轻量级循环称为列表解析(list comprehension,也译作列表推导式)。85列表解析的语法形式列表解析中的多个for语句相当于是for结构的嵌套使用86[ 表达式 for 表达式1 in 序列1for 表达式2 in 序列2…for 表达式N in 序列Nif 条件 ]列表解析87>>> [x for x in range(10)][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Source创建一个从0到9的简单的整数序列;列表解析88>>> [x ** 2 for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Source对range(10)中每一个值求平方数;列表解析89>>> [x ** 2 for x in range(10) if x ** 2 < 50][0, 1, 4, 9, 16, 25, 36, 49]Source对range(10)中的每一个值加入if语句“if x ** 2 < 50”,只生成比50小的平方数;列表解析90>>> [(x + 1,y + 1) for x in range(2) for y in range(2)][(1, 1), (1, 2), (2, 1), (2, 2)]Source使用嵌套的for语句。(x + 1, y + 1)的所有组合就包含了x从0-1,y也从0-1的变化。例5.12 列表解析方法91>>> pdlList = ['C++', 'Java', 'Python']>>> creditList = [2, 3, 4]>>> [(pdl, credit) for pdl in pdlList for credit in creditList][('C++', 2), ('C++', 3), ('C++', 4), ('Java', 2), ('Java', 3), ('Java', 4), ('Python', 2), ('Python', 3), ('Python', 4)]Source小结顺序结构选择结构循环结构列表解析92939495习题969798 展开更多...... 收起↑ 资源预览