Download presentation

Presentation is loading. Please wait.

Published byElisabeth Hargreaves Modified over 2 years ago

1
4 If-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming

2
4-2 If-statements: basic form An if-statement enables a program to choose between alternative courses of action. The basic form of if-statement is: if expression : body 1 else: body 0 a sequence of statements To execute this if-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body 1. 3. If the result was False, execute body 0.

3
4-3 Example: maximum of two numbers If max were not a built-in function, we could define it ourselves: def max (x, y): # Return the greater of the numbers x and y. if x > y: return x else: return y

4
4-4 If-statements: form without else Sometimes one of the alternatives of an if- statement is to do nothing. We can omit the else part: if expression : body To execute this if-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body 1. 3. If the result was False, do nothing.

5
4-5 Example: sorting two numbers The following program takes two numbers in x and y, and sorts them so that the smaller number is in x and the larger in y : x = input('Enter a number: ') y = input('Enter another number: ') if x > y: # Swap the numbers in x and y … z = x x = y y = x print 'Sorted numbers:', x, y

6
4-6 If-statements: extended form (1) Sometimes an if-statement has three (or more) alternatives. We can use an extended form of if-statement: if expression 1 : body 1 elif expression 2 : body 2 else: body 0 may be replicated as often as you need may be omitted

7
4-7 If-statements: extended form (2) This is equivalent to: if expression 1 : body 1 else: if expression 2 : body 2 else: body 0

8
4-8 Example: roots of quadratic equation (1) Consider the general quadratic equation: ax 2 + bx + c = 0 Its roots are given by: ( ‒ b ± √(b 2 – 4ac)) / (2a) But note that: –there are two real roots if b 2 – 4ac > 0 –there is only one real root if b 2 – 4ac = 0 –there are no real roots if b 2 – 4ac < 0.

9
4-9 Example: roots of quadratic equation (2) Function: def roots (a, b, c): # Return the real root(s) of the quadratic equation # a x 2 + b x + c = 0, or ( ) if it has no real roots. d = b**2 – 4*a*c if d > 0: s = square_root(d) r1 = (-b+s)/(2*a) r2 = (-b-s)/(2*a) return (r1, r2) elif d == 0: return –b/(2*a) else: return ()

10
4-10 Example: roots of quadratic equation (3) Function calls: roots(1.0, 2.0, 1.0) returns ‒ 1.0 roots(1.0, 3.0, 1.0) returns ( ‒ 0.382, ‒ 2.618) roots(1.0, 1.0, 1.0) returns ( )

11
4-11 Example: roots of quadratic equation (4) Tracing the function call roots(1.0, 2.0, 1.0) : abc Enter the function: 1.02.01.0 Execute “ d = b**2 - … ”: 1.02.01.0 d 0.0 Test “ d > 0 ”: yields False 1.02.01.00.0 Test “ d == 0 ”: yields True 1.02.01.00.0 Execute “ return –b/(2*a) ”: returns ‒ 1.0 1.02.01.00.0

12
4-12 Testing non-boolean values Uniquely, Python allows a value of any type to be tested in an if-statement (or while-statement). TypeValue treated as False Values treated as True integer0non-zero integers floating-point0.0non-zero numbers string‘’ (empty string)non-empty strings listempty listnon-empty lists dictionaryempty dictionarynon-empty dict’s

13
4-13 Example: testing strings Here is part of a simple command-line program. It accepts commands “duck” and “dive”, and rejects an invalid command. com = raw_input('Command? ') if com == 'duck': duck() elif com == 'dive': dive() elif com: print '- invalid command!' This assumes that functions duck and dive actually execute the respective commands. alternatively, elif com != '':

14
4-14 Conditional expressions A conditional expression evaluates its result in one of two alternative ways, depending on a boolean. It has the form: expression 1 if expression 0 else expression 2 To evaluate this conditional expression: 1. Evaluate expression 0 to either True or False. 2. If the result was True, evaluate expression 1. 3. If the result was False, evaluate expression 2.

15
4-15 Example: conditional expression (1) Here are shorter implementations of the abs and max functions: def abs (x): # Return the absolute value of the number x. return (x if x >= 0 else -x) def max (x, y): # Return the greater of the numbers x and y. return (x if x > y else y) It is good practice to parenthesise this form of expression.

16
4-16 Boolean operators revisited Consider an expression of the form “A and B”. –A is evaluated first. If it yields False, the overall result must be False, so B is not evaluated at all. –Thus “A and B” is equivalent to “B if A else False ”. Similarly, consider an expression of the form “A or B”. –A is evaluated first. If it yields True, the overall result must be True, so B is not evaluated at all. –Thus “A or B” is equivalent to “ True if A else B”.

17
4-17 Short-circuit evaluation The boolean operators “ and ” and “ or ” each uses short-circuit evaluation. The right operand is evaluated only if it can affect the overall result. No other Python operator uses short-circuit evaluation. The left and right operands are both evaluated.

18
4-18 Example: short-circuit evaluation (1) This function tests whether a student is qualified to graduate with an ordinary degree: def qualified (credits, grade_points): # Return True if the student has at least 360 credits # and a grade-point average of at least 9.0. return credits >= 360 and grade_points/credits >= 9.0 If the student has 0 credits, this function correctly returns False. Short-circuit evaluation is essential here, otherwise the function would fail (division by 0).

19
4-19 Example: short-circuit evaluation (2) This function uses a conditional expression to give the same result: def qualified (credits, grade_points): # Return True if the student has at least 360 credits # and a grade-point average of at least 9.0. return (grade_points/credits >= 9.0 \ if credits >= 360 \ else False)

Similar presentations

OK

1 Functional Programming Lecture 8 - Binary Search Trees.

1 Functional Programming Lecture 8 - Binary Search Trees.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on environment and sustainable development class 11 Ppt on power system harmonics calculation Ppt on eddy current suppression Ppt on earthquake resistant buildings in india Ppt on statistics in maths what is the product Ppt on acid-base titration curves Mis ppt on hospital waste Ppt on boilers operations with integers Ppt on reported speech in english grammar Ppt on organizational culture and values