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

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

Embed Size (px)

Citation preview

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

4If-Statements

© 2010 David A Watt, University of Glasgow

Accelerated Programming 2

Part I: Python Programming

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

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: body1

else: body0

a sequence of statements

a sequence of statements

To execute this if-statement:

1. Evaluate expression to either True or False.2. If the result was True, execute body1.3. If the result was False, execute body0.

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

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

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

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 body1.3. If the result was False, do nothing.

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

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 = xprint 'Sorted numbers:', x, y

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

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 expression1: body1

elif expression2: body2

else: body0

may be replicated as often as you need

may be omitted

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

4-7

If-statements: extended form (2)

This is equivalent to:

if expression1: body1

else: if expression2: body2

else: body0

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

4-8

Example: roots of quadratic equation (1)

Consider the general quadratic equation:

ax2 + bx + c = 0

Its roots are given by:

(‒b ± √(b2 – 4ac)) / (2a)

But note that:

– there are two real roots if b2 – 4ac > 0

– there is only one real root if b2 – 4ac = 0

– there are no real roots if b2 – 4ac < 0.

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

4-9

Example: roots of quadratic equation (2)

Function:

def roots (a, b, c): # Return the real root(s) of the quadratic equation # ax2 + bx + 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 ()

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

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 ( )

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

4-11

Example: roots of quadratic equation (4)

Tracing the function call roots(1.0, 2.0, 1.0):

a b cEnter the function: 1.0 2.0 1.0

Execute “d = b**2 - …”: 1.0 2.0 1.0

d0.0

Test “d > 0”: yields False 1.0 2.0 1.0 0.0

Test “d == 0”: yields True 1.0 2.0 1.0 0.0

Execute “return –b/(2*a)”: returns ‒1.0 1.0 2.0 1.0 0.0

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

4-12

Testing non-boolean values

Uniquely, Python allows a value of any type to be tested in an if-statement (or while-statement).

Type Value treated as False

Values treated as True

integer 0 non-zero integers

floating-point 0.0 non-zero numbers

string ‘’ (empty string) non-empty strings

list empty list non-empty lists

dictionary empty dictionary non-empty dict’s

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

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 != '':

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

4-14

Conditional expressions

A conditional expression evaluates its result in one of two alternative ways, depending on a boolean.

It has the form:

expression1 if expression0 else expression2

To evaluate this conditional expression:

1. Evaluate expression0 to either True or False.2. If the result was True, evaluate expression1.3. If the result was False, evaluate expression2.

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

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.

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

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”.

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

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.

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

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).

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

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)