Introduction to Computer Programming School of Computer and Information Science Southwest Forestry University 2012.9 Chapter 3 Conditional Statements Danju Lv Autumn semester , 2012 Chap3 Conditional Statements REVIEW Definition of Conditional Statements Logical judgment and conditional expression 条件语句的定义 if statement 逻辑判断与条件表达式 else statement 单分支语句 双分支语句 elif statement 多分支语句 Mix of conditionals 条件嵌套语句 Chap3 conditional statements 条件语句是根据条件表达式的值是True/not zero 还是False/zero做出决策,控制执行的代码块。 4 key points Expression Value of the Expression Control Block of Code/suit 4个要点: 表达式 值 控制 代码块 if 单分支语句 if expression: expr_true_suite The suite of the if clause, expr_true_suite, will be executed only if the above conditional expression results in a Boolean true value. Otherwise, execution resumes at the next statement following the suite. If 语句:若表达式为真/非零则 执行冒号后的语句块,若表达式为 假则跳过该语句块的执行。 False 表达式 True true语句块 Exp of if statement 【例3-2】 Input the radius of the circle from the keyboard, if the radius is larger than or equal to zero , then calculate the area of circle. 开始 输入半径 False 半径不小于0 True 计算圆面积 输出圆面积 结束 import math r=eval(input(‘请输入圆的半径:’)) if r>=.0: s=math.pi*r**2 print("s=pi*r*r=",s) 结果验证: 请输入圆的半径:4 s=pi*r*r= 50.26548245743669 Think 1. When input r is negative number, what’s the result? What we will see on the screen? 2. The output of the program could be improved? Such as when the input r is negative, give a prompt input error message, when the input r is non-negative, calculate the area of the circle. Else statement 双语句分支 Syntax of else statement: if 表达式 : if expression: expr_true_suite Ture语句块 else: else : expr_false_suite False语句块 表达式 False True Ture语句块 False语句块 图3-4 双分支语句的执行方式 The else statement identifies a block of code( expre false suite) to be executed if the conditional expression of the if statement resolves to a false Boolean value. Understanding of else statement 请画出以下程序的框图结构,该程序的执行路线如 何,结果是?若程序的x=2替换为x=-2,程序的执 行路线又如何,结果? X=2 x=2 if x > 0: y = 1+2*x else: y=0 print('y=', y) x>0 False True y=1+2*x print(‘y=’,y) y=0 Eg. Of Else Statements Eg3_3. input an integer from the keyboard, if it is even, then print “even” ; if it is odd, then print "odd". [Analyze:] An integer is either an even number or an odd number, so it is an else statement case The variable settings 变量的设置 The conditional expression 条件表达式的表示 Choose the right conditional statements 条件结构的确定 Block diagram start 1. 使用 input(): 获取一个整数 2. 使用“=“ 将从键盘获取的数存 于变量X Get num. from the keyboard 1. Use input(): get a integer 2. Use “=“ save the num. in x variable from the keyboard False X%2==0 or x%2 is 0 x被2整除? True 输出“偶数” end 输出“奇数” Use print() show the result program start Get num. from the keyboard False x被2整除? if expression: expr_true_suite else: expr_false_suite #Exp3_3.py x=eval(input('请输入一个整数:')) if x%2==0: #judge an even print(‘偶数') else: print('奇数') True 输出“偶数” end 输出“奇数” 程序运行结果: 请输入一个整数:2 偶数 Eg. Of Else Statements 【eg3-4】Design a program for a telecommunications company interview job seekers. The program is to tell the job seekers whether meet the required educational conditions. If Job seekers meet one of the following conditions ,they will receive an interview notice, if not , they will receive a rejection notice. The educational conditions are the following: 为某电信公司面试求职者设计一程序。该程序是给满足 某些教育条件的求职者提供面试机会。满足如下条件的 求职者会接到面试通知: Educational conditions (1) at least 25 years of age , the electronic information engineering graduates. (2) Key Universities , Electronic Information Engineering graduates. (3) Under 28-year-old , computer science graduate Meet One of the above conditions can gain an interview (1)25岁以上,电子信息工程专业毕业生。 (2)重点大学电子信息工程专业毕业生。 (3)28岁以下,计算机专业毕业 满足以上条件之一即可获得面试机会 Eg of else statement 【分析】:变量的设置, 选择表达式, 分支语句 1.分析条件可知公司面试条件涉及3个方面:年龄 、所学专业和毕业学校。为此设定3个变量(age ,subject和college)分别表示; 2.选择条件设置:3个条件只需满足其中一个即可 ,其逻辑关系应为:或者or;而在每一个条件里涉 及的方面又应为“与and”的逻辑关系。 3.分支判断:若满足如上复合条件,则显示“恭喜 ,你已获得我公司的面试机会”,否则显示“抱歉, 你未达到面试要求”。 开始 Block of Diagram age=24 subject="计算机" college="非重点" age > 25 and subject=="电子信息工程" or college=="重点" and subject=="电子信息工程" or age<=28 and subject=="计算机" False True 显示"恭喜,你已获得 我公司的面试机!" 结束 显示"抱歉,你未达到面 试要求" Program (1)25岁以上,电子信息工程专业毕业生。 (2)重点大学电子信息工程专业毕业生。 (3)28岁以下,计算机专业毕业 满足以上条件之一即可获得面试机会 #程序: #Exp3-6.py age=24 subject="计算机" college="非重点" if (age > 25 and subject=="电子信息工程")\ or (college=="重点" and subject=="电子信息工程" )\ or (age<=28 and subject=="计算机"): print(“恭喜,你已获得我公司的面试机会!") else: print(“抱歉,你未达到面试要求“) 程序运行结果: 恭喜,你已获得我公司的面试机会! Think 例题中,作为面试者的条件是在源程序中进行设定的,如何 获取求职者三方面的信息呢?可以在程序中设置3个问题: 哪所学校毕业?学的专业是什么?求职者的年龄? 1. 毕业的学校是重点院校吗?(1/2): 1.重点 2. 非重点 2.学的专业是什么?(1/2/3): 1.电子信息工程;2.计算 3.其它 3. 你的年龄? 此时程序应如何改动呢? “Dangling else” avoidance Python's design of using indentation rather than braces for code block delimitation not only helps to enforce code correctness, but it even aids implicitly in avoiding potential problems in code that is syntactically correct. One of those such problems is the (in)famous "dangling else" problem, a semantic optical illusion. Diagram Please draw diagram for those programs. And tell the results of those programs under the balance is negative or positive. elif statement Syntax of elif statement if expression1: expr1_true_suite elif expression2: expr2_true_suite …. elif expressionN: exprN_true_suite else: It allows one to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true. Like the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. none_of_the_above_suite Block of diagram of elif statement if expression1: expr1_true_suite elif expression2: expr2_true_suite 表达式1 False arbitrary number of elif Ture Ture_expr1 _suit …. elif expressionN: exprN_true_suite else: none_of_the_above_suite 表达式1 表达式2 …… False Ture T Ture_expr2 _suit 表达式n False Ture Ture_exprN None of the _suit above_suit …… 分支结束 Eg. Of elif Statement [3-5]Grade student achievement by computer (Fail, Pass, intermediate, Good, Excellent). Its criteria for the classification : Fail is less than 60; 60 to 70 are classified as Pass, 70 to 80 are divided into Intermediate 80 to 90 divided into Benign 90 to 100-Excellent. Finally, display its class information Analyze 1. Variable setting Where to get date, how to save date 2. Expression Comparison expr. 3. Conditions Elif statement Diagram of Example 开始 键盘输 入score Score<0 or score >100 False Ture Score<60 False Ture T 无效成绩 False Score<70 Ture False 不及格 Score<80 及格 Ture False Score<90 中等 Ture 良好 程序结束 优秀 Program 程序 score=eval(input('请输入你的成绩(0~100):')) if score<0 or score>100: print('无效的成绩') elif score<60: print('不及格') elif score<70: print('及格') elif score<80: print('中等') elif score<90: print('良好') else: print('优秀') 程序运行结果: 请输入你的成绩(0~100):88 良好 选择结构的嵌套 在某一个分支的语句块中,需要进行新的分支。这 种结构你为选择结构的嵌套。嵌套的形式如下: if 表达式1: #语句块1 … if 表达式11: 语句块11… else: 语句块12 … else: 语句块2 选择程序举例 【例3-6】选择结构的嵌套问题。购买地铁车票的 规定如下: 乘1-4站,3元/位;乘5-9站,4元/位;乘9站以上 ,5元/位。 输入人数、站数,输出应付款。 分析:需要进行两次分支。根据“人数<=4”分支一 次,表达式为假时,还需要根据“人数<=9”分支一 次。 程序框图 开始 输入人数n、站数m False m<=4 True pay=3*n 输出应付款 结束 图3-9 计算乘地铁应付款 m<=9 True pay=4*n False pay=5*n 程序 #Exp3_5.py n, m=eval(input('请输入数,站数:')) if m<=4: pay=3*n else: if m<=9: pay=4*n else: 输入及程序运行结果: pay=5*n print('应付款:', pay) 请输入数,站数:3,5 应付款: 12 Chapter Summarizes Conditional statements If statement Else statement Elif statement Mix/nested of conditional statement Deeply understand control structure Core: the value of the expr. control the execution of suits/blocks of code.