Principles of Programming CM10227 Lecture D.2.: Conditionals, - - PowerPoint PPT Presentation

principles of programming cm10227
SMART_READER_LITE
LIVE PREVIEW

Principles of Programming CM10227 Lecture D.2.: Conditionals, - - PowerPoint PPT Presentation

Conditionals More on Functions Recursion Principles of Programming CM10227 Lecture D.2.: Conditionals, Recursion, Interesting Functions Dr. Marina De Vos University of Bath Ext: 5053 Academic Year 2012-2013 Lecture D.2. (MDV) Programming


slide-1
SLIDE 1

Conditionals More on Functions Recursion

Principles of Programming CM10227

Lecture D.2.: Conditionals, Recursion, Interesting Functions

  • Dr. Marina De Vos

University of Bath Ext: 5053

Academic Year 2012-2013

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 1 / 60

slide-2
SLIDE 2

Conditionals More on Functions Recursion

Outline

1

Conditionals

2

More on Functions

3

Recursion

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 2 / 60

slide-3
SLIDE 3

Conditionals More on Functions Recursion

Outline

1

Conditionals

2

More on Functions

3

Recursion

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 2 / 60

slide-4
SLIDE 4

Conditionals More on Functions Recursion

Outline

1

Conditionals

2

More on Functions

3

Recursion

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 2 / 60

slide-5
SLIDE 5

Conditionals More on Functions Recursion

Resources

How to Think Like a Computer Scientist: Python Version : Chapter 4 -5 http: //greenteapress.com/thinkpython/thinkCSpy/ Introduction to Programming http://eric_rollins. home.mindspring.com/introProgramming/ Introduction to Python http://www.slideshare.net/ amiable_indian/introduction-to-python http://osl.iu.edu/˜lums/swc/www/index.html Python Tutorial http://docs.python.org/tut/tut.html

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 3 / 60

slide-6
SLIDE 6

Conditionals More on Functions Recursion Operators Conditional Execution

Outline

1

Conditionals Operators Conditional Execution

2

More on Functions

3

Recursion

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 4 / 60

slide-7
SLIDE 7

Conditionals More on Functions Recursion Operators Conditional Execution

The Modulo Operator

The modulo operator works on integers (and integer expressions) yields the remainder when the first operand is divided by the second. the modulo operator is a percent sign,%.

> > > quotient = 7/3 > > > remainder = 7 % 3 > > > quotient 2 > > > remainder 1

✡ ✝ ✆

if x % y is zero, then x is divisible by y x % 10 yields the rightmost digit of x (in base 10) x % 100 yields the last two digits

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 5 / 60

slide-8
SLIDE 8

Conditionals More on Functions Recursion Operators Conditional Execution

Booleans

True and False are true and false

Empty string, 0, and None are equivalent to False (but not the same)

Just as 3 is equivalent to 3.0

(Almost) everything else is true Combine Booleans using and, or, not

and and or are short-circuit operators Evaluate expressions left to right, and stop as soon as they know the answer

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 6 / 60

slide-9
SLIDE 9

Conditionals More on Functions Recursion Operators Conditional Execution

Booleans II

Expression Result Notes True or False True True and False False ’a’ or ’b’ ’a’

  • r is true if either side is true, so it

stops after evaluating ’a’ ’a’ and ’b’ ’b’ and is only true if both sides are true, so it doesn’t stop until it has evaluated ’b’ 0 or ’b’ ’b’ 0 is false, but ’b’ is true 0 and ’b’ Since 0 is false, Python can stop evaluating there 0 and (1/0) 1/0 would be an error, but Python never gets that far (x and ’set’) or ’not set’ It depends If x is true, this expression’s value is ’set’; if x is false, it is ’not set’

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 7 / 60

slide-10
SLIDE 10

Conditionals More on Functions Recursion Operators Conditional Execution

Comparisons I

We can compare values or expressions that evaluate to numbers in the following way: Expression Value 3 < 5 True 3.0 < 5 True 3 ! = 5 True 3 == 5 False 3 < 5 <= 7 True 3 < 5 >= 2 True (but please don’t write this: it’s hard to read) All datatypes can be compared using == and !=

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 8 / 60

slide-11
SLIDE 11

Conditionals More on Functions Recursion Operators Conditional Execution

Comparisons II

Note the difference between assignment and testing for equality

Use a single equals sign = for assignment Use a double equals sign == to test if two things have equal values

String comparison may not do what you expect:

Characters are encoded as numbers: digits come before uppercase letters, all of which come before lowercase letters, with punctuation is mixed in between, just to make matters difficult Strings are compared character by character:

One character is less than another One string runs out of characters Expression Value ’abc’ < ’def’ True ’abc’ < ’Abc’ False ’ab’ < ’abc’ True ’0’ < ’9’ True ’100’ < ’2’ True

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 9 / 60

slide-12
SLIDE 12

Conditionals More on Functions Recursion Operators Conditional Execution

Conditionals

Definition Conditional statements allow us to check certain conditions and change the behavior of the program accordingly. The simplest form is the if statement:

i f x > 0: print ” x i s p o s i t i v e ”

✡ ✝ ✆

The expression between the if and the : is called the condition.

If it is true, then the indented statement(s) get executed. If it is not true, nothing happens (the indented statements are skipped).

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 10 / 60

slide-13
SLIDE 13

Conditionals More on Functions Recursion Operators Conditional Execution

Conditionals

The condition can be any expression that evaluates to a Boolean

boolean expressions comparisons functions with a boolean as a return value

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 11 / 60

slide-14
SLIDE 14

Conditionals More on Functions Recursion Operators Conditional Execution

Compound Statements

if statements, like function definitions, are compound statements. Their syntax is:

HEADER: FIRST STATEMENT . . . LAST STATEMENT

✡ ✝ ✆

The header begins on a new line and ends with a colon. The indented statements that follow are called a statement block. The first unindented statement marks the end of the block

All the statements in the block are treated as a unit.

In the case of an if statement, either all of them or none of them are executed.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 12 / 60

slide-15
SLIDE 15

Conditionals More on Functions Recursion Operators Conditional Execution

Alternative execution

A second form of the if statement is alternative execution, in which there are two possibilities, and the condition determines which one gets executed:

i f x%2 == 0: print x , ” i s even ” else : print x , ” i s odd ”

✡ ✝ ✆

This code could be wrapped in a function:

def p r i n t P a r i t y ( x ) : i f x%2 == 0: print x , ” i s even ” else : print x , ” i s odd ”

✡ ✝ ✆ ✞

> > > p r i n t p a r i t y (17) 17 is odd . > > > y = 41 > > > p r i n t p a r i t y ( y+1) 42 is even .

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 13 / 60

slide-16
SLIDE 16

Conditionals More on Functions Recursion Operators Conditional Execution

Multiple branches

Another name for conditional execution is conditional branching, because this type of control structure causes the flow of execution to branch off in different directions.

if is extended to multiple

branches with the elif (an abbreviation for ”else if”).

i f x < y : print x , ” i s less than ” , y e l i f x > y : print x , ” i s greater than ” , y else : print x , ” and ” , y , ” are equal ”

✡ ✝ ✆

multiple elif can also be repeated:

i f choice == ’A ’ : functionA ( ) e l i f choice == ’B ’ : functionB ( ) e l i f choice == ’C ’ : functionC ( ) e l i f choice == ’D ’ : functionD ( ) else : print ” I n v a l i d choice . ”

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 14 / 60

slide-17
SLIDE 17

Conditionals More on Functions Recursion Operators Conditional Execution

Nested conditionals

One conditional can also be nested inside another:

i f x == y : print x , ” and ” , y , ” are equal ” else : i f x < y : print x , ” i s less than ” , y else : print x , ” i s greater than ” , y

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 15 / 60

slide-18
SLIDE 18

Conditionals More on Functions Recursion Operators Conditional Execution

Return statements in Conditionals

If you put return statements inside a conditional, then you have to guarantee that every possible path through the program hits a return statement. For example:

def absoluteValue ( x ) : i f x < 0: return −x e l i f x > 0: return x # PROBLEM! !

✡ ✝ ✆

If x is 0, the function will end with out hitting a return

  • statement. The return value will instead be a special value

called None:

> > > print absoluteValue (0) None

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 16 / 60

slide-19
SLIDE 19

Conditionals More on Functions Recursion Operators Conditional Execution

More on Return Statements

In Python, all functions have a return value, even those that do not have an explicit return statement. Those are returning the special value none In some programming languages this is not the case. One then refers to the non-returning ”functions” as procedures A return statement ends the execution of the function. Control is passed back. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 17 / 60

slide-20
SLIDE 20

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Outline

1

Conditionals

2

More on Functions Typing Call stack and Scope More on Parameters Program Design

3

Recursion

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 18 / 60

slide-21
SLIDE 21

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Typing in Programming Languages I

statically typed language A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages. dynamically typed language A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 19 / 60

slide-22
SLIDE 22

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Typing in Programming Languages II

strongly typed language A language in which types are always

  • enforced. Java and Python are strongly typed. If

you have an integer, you can’t treat it like a string without explicitly converting it. weakly typed language A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string ’12’ and the integer 3 to get the string ’123’, then treat that as the integer 123, all without any explicit conversion.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 20 / 60

slide-23
SLIDE 23

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Typing in Python

Python is: dynamically typed: because it doesn’t use explicit datatype declarations strongly typed: because once a variable has a datatype, it actually matters.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 21 / 60

slide-24
SLIDE 24

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Type conversion I

Python provides a collection of built-in functions to convert values from one type to another. The int function takes any value and coverts it to an integer, if possible, or complains otherwise:

> > > i n t ( ” 32 ” ) 32 > > > i n t ( ” Hello ” ) ValueError : i n v a l i d l i t e r a l for i n t ( ) : Hello

✡ ✝ ✆

int can also convert floating-point values to integer, but

remember that it always rounds down:

> > > i n t (3.99999) 3

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 22 / 60

slide-25
SLIDE 25

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Type conversion II

The float function converts integers and strings:

> > > f l o a t (32) 32.0 > > > f l o a t ( ” 3.14159 ” ) 3.14159

✡ ✝ ✆

The str function converts to type string:

> > > s t r (32) ’ 32 ’ > > > s t r (3.14149) ’ 3.14149 ’

✡ ✝ ✆

And remember Python distinguishes the integer value 1 from the floating point value 1.0.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 23 / 60

slide-26
SLIDE 26

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Type coercion

Recall the problem we had with integer division: minute / 60 We have two possible solutions: explicit conversion to float:

> > > minute = 59 > > > f l o a t ( minute ) / 60.0 0.983333333333

✡ ✝ ✆

type coercion For mathematical operators, if either operand is a float, the

  • ther is automatically converted to a float.

> > > minute = 59 > > > minute / 60.0 0.983333333333

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 24 / 60

slide-27
SLIDE 27

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Memory Stack I

A stack can be seen as a pile of plates. Clean plates go on top and plates are always taken from to top. So a stack works: FILO: First In Last Out Every time you call a function or a procedure is called memory is allocated on the memory stack to store the parameters and local variables, blocking access to what is below.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 25 / 60

slide-28
SLIDE 28

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Memory Stack II

When a variable is referenced, Python looks at the top stack frame, then at global variables Fresh copies are created for each call Values discarded when the function returns As always, variables must be defined before they can be used The global variables are stored on the bottom of the stack at the layer referred to as

main

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 26 / 60

slide-29
SLIDE 29

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Example: Memory Stack

def catTwice ( part1 , part2 ) : # concatenates arguments ; p r i n t s twice cat = part1 + part2 printTwice ( cat ) def printTwice ( arg ) : print arg ∗ 2 chant1 = ” Python , ” chant2 = ”THE programming language . ” catTwice ( chant1 , chant2 )

✡ ✝ ✆ ✞

Python , THE programming language . Python , THE programming language .

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 27 / 60

slide-30
SLIDE 30

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Example: Stack Diagram

chant1 − > Python, chant2 − > THE programming language. part1 − > Python, part2 − > THE programming language. cat − > Python, THE programming language. arg − > Python, THE programming language. main catTwice printTwice

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 28 / 60

slide-31
SLIDE 31

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Traceback

def p r i n t t w i c e ( bruce ) : print bruce , bruce print cat # notice cat has not been defined . def cat twice ( part1 , part2 ) : cat = part1 + part2 p r i n t t w i c e ( cat ) chant1 = ” Python i s great . ” chant2 = ” Python i s fun . ” cat twice ( chant1 , chant2 )

✡ ✝ ✆ ✞

Traceback ( innermost l a s t ) : F i l e ” t e s t . py ” , l i n e 11 , in <module> cat twice ( chant1 , chant2 ) F i l e ” t e s t . py ” , l i n e 7 , in cat twice p r i n t t w i c e ( cat ) F i l e ” t e s t . py ” , l i n e 3 , in p r i n t t w i c e print cat NameError : global name ’ cat ’ is not defined

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 29 / 60

slide-32
SLIDE 32

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Scope

Global variables are defined in area called

main

These variables can be accessed from everywhere Variables and parameters can only be accessed within the function there are defined The area in which a variable can be referenced is called the scope of the variable In Python indentation defines the scope of a variable. We say that the scope of the function is nested in the global scope Each compound statement defines its own scope, nested in the scope of the enclosing function or in the global area

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 30 / 60

slide-33
SLIDE 33

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Name Overloading

# Global variable called ’ x ’ . x = 123 # Function that defines a l o c a l variable called ’ x ’ . def f ( arg ) : x = arg print ” in ca l l , x i s ” , x

✡ ✝ ✆ ✞

# Call the function to prove that i t uses i t s l o c a l ’ x ’ . print ” before ca l l , global x i s ” , x f (999) print ” a f t e r ca l l , global x i s ” , x before ca l l , global x is 123 in ca l l , x is 999 a f t e r ca l l , global x is 123

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 31 / 60

slide-34
SLIDE 34

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Name Overloading II

Notice that we have both a global variable and local variable with the name x This called name overloading With nested scopes, Python will always look at the local scope first before going the the global one to find the value

  • f variable name.

Follow the indentation outwards

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 32 / 60

slide-35
SLIDE 35

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Name Overloading

Globals Heap Stack x 123

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 33 / 60

slide-36
SLIDE 36

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Name Overloading

Globals Heap Stack x arg f 123 999

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 33 / 60

slide-37
SLIDE 37

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Name Overloading

Globals Heap Stack x arg x f 123 999

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 33 / 60

slide-38
SLIDE 38

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Parameter Passing

There are generally two ways in passing parameters: Call-by-Value: When an argument is passed to a function, the parameter will receive a copy of the the argument. This means that the argument will not have changed after the function call. Call-by-Reference: When arguments are passed to a function, the parameters will receive the arguments references. This implies that everything that happens to the parameter will have an effect on the argument

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 34 / 60

slide-39
SLIDE 39

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Parameter Passing in Python

Python copies variables’ values when passing them to functions But, these values are references to memory. The fact that references are copied plays an important part when working with changeable datatypes as we will see next week.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 35 / 60

slide-40
SLIDE 40

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Incremental Development

Now we will discuss how to write functions from scratch. We will use a technique called incremental development. Example: find distance between two points, given by coordinates (X1, y1) and (x2, y2). By the usual definition, with sqrt representing the square root function, distance = sqrt((x2 − x1)2 + (y2 − y1)2) What should a distance function look like in Python? What are the inputs (parameters), and what is the output (return value)? The parameters are the two points, which we can represent using four parameters. The return value is the distance.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 36 / 60

slide-41
SLIDE 41

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Base Program

Outline of the function:

def distance ( x1 , y1 , x2 , y2 ) : return 0.0

✡ ✝ ✆

The return value is a placeholder. This way we can test it:

> > > def distance ( x1 , y1 , x2 , y2 ) : . . . return 0.0 . . . > > > distance (1 , 2 , 4 , 6) 0.0 > > >

✡ ✝ ✆

Here we know the right answer is 5

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 37 / 60

slide-42
SLIDE 42

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Increment 1

Now find differences x2 - x1 and y2 - y1. We will store those values in temporary variables named dx and dy:

def distance ( x1 , y1 , x2 , y2 ) : dx = x2 − x1 dy = y2 − y1 print ” dx i s ” , dx print ” dy i s ” , dy return 0.0

✡ ✝ ✆

The printed values should be 3 and 4. The print statements are for use in testing:

Scaffolding: useful for building the program, but not part of final product. can comment it out, in case you need it later.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 38 / 60

slide-43
SLIDE 43

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Final Increments

Now square dx and dy:

def distance ( x1 , y1 , x2 , y2 ) : dx = x2 − x1 dy = y2 − y1 dsquared = dx∗∗2 + dy∗∗2 print ” dsquared i s : ” , dsquared return 0.0

✡ ✝ ✆

The printed value should be 25. Finally,

import math def distance ( x1 , y1 , x2 , y2 ) : dx = x2 − x1 dy = y2 − y1 dsquared = dx∗∗2 + dy∗∗2 r e s u l t = math . sqrt ( dsquared ) return r e s u l t

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 39 / 60

slide-44
SLIDE 44

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Incremental Design II

The key aspects of incremental development are: Start with a working program and make small incremental changes.

If there is an error, you will know exactly where it is.

Use temporary variables to hold intermediate values so you can output and check them. Once program is working, remove scaffolding or consolidate multiple statements into compound expressions.

Do not do this if it makes program more difficult to read.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 40 / 60

slide-45
SLIDE 45

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Composition and Chaining I

Function definitions can be composed from other functions. Example: given two points, the center of the circle and a point on the perimeter, what is the area of the circle? Assume center point is xc,yc and perimeter point is xp,yp. First find radius of circle, which is distance between the two points: radius = distance(xc, yc, xp, yp) Now find area of circle with that radius, and return it:

r e s u l t = area ( radius ) return r e s u l t

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 41 / 60

slide-46
SLIDE 46

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Composition and Chaining II

Wrapping it all in a function:

def area2 ( xc , yc , xp , yp ) : radius = distance ( xc , yc , xp , yp ) r e s u l t = area ( radius ) return r e s u l t

✡ ✝ ✆

We called this function area2 to distinguish it from the area function defined earlier. There can only be one function of a given name within a given module. We can make the function more concise:

def area2 ( xc , yc , xp , yp ) : return area ( distance ( xc , yc , xp , yp ) )

✡ ✝ ✆

calling a function with the result of another function is called chaining

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 42 / 60

slide-47
SLIDE 47

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Robust Code

Some functions and expressions only work for certain types or values of parameters.

def d i v i s i o n 1 (a , b ) : return a / b

✡ ✝ ✆ ✞

> > > d i v i s i o n 1 (8 ,4) 2 > > > d i v i s i o n 1 ( ” s t r i n g ” , ” d i v i s i o n ” ) Traceback ( most recent c a l l l a s t ) : F i l e ”<pyshell#1>” , l i n e 1 , in ? d i v i s i o n 1 ( ” s t r i n g ” , ” d i v i s i o n ” ) F i l e ” /home/mdv/ Desktop / teaching / Programming / Doubles / Lecture2 / div . py ” , l i n e 2 , in d i v i s i o n 1 return a / b TypeError : unsupported operand type ( s ) for / : ’ s t r ’ and ’ s t r ’

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 43 / 60

slide-48
SLIDE 48

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Robust Code II

The user might not be aware of this Your code should endeavour to exit gracefully when wrong input is provided In other words, your code has to made robust This can be done by setting up guardians that verify the date or value or parameters before letting the function proceed to its normal business The guardians make it possible to prove the correctness of the code

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 44 / 60

slide-49
SLIDE 49

Conditionals More on Functions Recursion Typing Call stack and Scope More on Parameters Program Design

Robust Code III

def d i v i s i o n 2 (a , b ) : i f ( ( type ( a ) == type (1) ) & ( type ( b ) == type (1) ) ) : return a / b else : print ” Sorry , t h i s function can only deal with integers ” return −1

✡ ✝ ✆ ✞

> > > d i v i s i o n 2 (8 ,4) 2 > > > d i v i s i o n 2 ( ” s t r i n g ” , ” d i v i s i o n ” ) Sorry , t h i s function can only deal with integers −1 > > >

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 45 / 60

slide-50
SLIDE 50

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Outline

1

Conditionals

2

More on Functions

3

Recursion Examples The Nature of the Beast Stack and Traces

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 46 / 60

slide-51
SLIDE 51

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Recursion: A first Example

def countdown ( n ) : i f n == 0: print ” B l a s t o f f ! ” else : print n countdown (n−1)

✡ ✝ ✆

Functions, besides calling other functions, can also call themselves. This is one of the most magical and interesting things a program can do. The process of a function calling itself is called recursion Such functions are said to be recursive

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 47 / 60

slide-52
SLIDE 52

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Another example

def newline ( ) : print def threeLines ( ) : newLine ( ) newLine ( ) newLine ( )

✡ ✝ ✆ ✞

def nLines ( n ) : i f n > 0: print nLines (n−1)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 48 / 60

slide-53
SLIDE 53

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Another example

def newline ( ) : print def threeLines ( ) : newLine ( ) newLine ( ) newLine ( )

✡ ✝ ✆ ✞

def nLines ( n ) : i f n > 0: print nLines (n−1)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 48 / 60

slide-54
SLIDE 54

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

What would happen?

def countdown ( n ) : print n countdown (n−1) # recursive step

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 49 / 60

slide-55
SLIDE 55

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Recursive Problem

Problem Specification They have at least one simple case (the base case) of the problem which can be solved without recursion all other cases can be reduced to a case closer to the base case by means of recursion eventually all cases can be reduced to the base case If recursion never reaches a base case it will continue making recursive calls forever. This is called infinite recursion. A finite amount of stack is consumed on each recursive call, and eventually the program will terminate with:

RuntimeError : Maximum recursion depth exceeded

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 50 / 60

slide-56
SLIDE 56

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

General Structure

Structure if base case is reached then SOLVE else REDUCE THE PROBLEM USING RECURSION Definition We number of reduction steps a problem is away from the base case is called the problem size.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 51 / 60

slide-57
SLIDE 57

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

A Slightly Larger Example

def reverse ( n ) : i f ( n <= 1) : c = raw input ( ” Please input a character . ” ) print c else : c = raw input ( ” Please input a character . ” ) reverse (n−1) print c

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 52 / 60

slide-58
SLIDE 58

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Trace

Trace of the Program Call Reverse with N = 3 Read first character (M) in c Call Reverse with N = 2 Read second character (D) in c Call Reverse with N = 1 Read third character (V) in c Write third character (V) Return to caller Write second character (D) Return to caller Write first character (M) Return to caller {the original caller in this case main programme}

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 53 / 60

slide-59
SLIDE 59

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Detail

the IF-statement contains the base case criteria this means that one more character needs to be read. this is last, so can be printed immediately the ELSE-statement reads in a character this cannot be printed before all remaining characters are read and printed this is done by recursive call so, we control returns, the characters can be printed This means that return from recursion occurs in reverse

  • rder from the recursive calls

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 54 / 60

slide-60
SLIDE 60

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > ? n − > 3 reverse(3) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-61
SLIDE 61

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 reverse(3) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-62
SLIDE 62

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > ? n − > 2 reverse(3) reverse(2) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-63
SLIDE 63

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > D n − > 2 reverse(3) reverse(2) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-64
SLIDE 64

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > D n − > 2 c − > ? n − > 1 reverse(3) reverse(2) reverse(1) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-65
SLIDE 65

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > D n − > 2 c − > V n − > 1 reverse(3) reverse(2) reverse(1) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-66
SLIDE 66

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > D n − > 2 c − > V n − > 1 reverse(3) reverse(2) reverse(1) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-67
SLIDE 67

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 c − > D n − > 2 reverse(3) reverse(2) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-68
SLIDE 68

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Stack and Output

c − > M n − > 3 reverse(3) Output Please input a character.M Please input a character.D Please input a character.V V D M

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 55 / 60

slide-69
SLIDE 69

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

tail recursion

the recursive call is the last statement in the function This is called tail recursion from a software engineering point of view it is a bad thing to do Not efficient because the heavy use of the call stack A better way to write such functions is to use iterations Iteration is more efficient both in terms of speed and memory usage than tail recursion There are plenty of cases, however, where using recursion is the best way to go, both in terms of computational elegance and efficiency.

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 56 / 60

slide-70
SLIDE 70

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Factorial

0! = 1 n! = n (n-1)!

def f a c t o r i a l ( n ) : i f type ( n ) != type (1) : print ” F a c t o r i a l i s

  • nly

defined f o r integers . ” return −1 e l i f n < 0: print ” F a c t o r i a l i s

  • nly

defined f o r p o s i t i v e integers . ” return −1 e l i f n == 0: return 1 else : return n ∗ f a c t o r i a l (n−1)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 57 / 60

slide-71
SLIDE 71

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Factorial

0! = 1 n! = n (n-1)!

def f a c t o r i a l ( n ) : i f type ( n ) != type (1) : print ” F a c t o r i a l i s

  • nly

defined f o r integers . ” return −1 e l i f n < 0: print ” F a c t o r i a l i s

  • nly

defined f o r p o s i t i v e integers . ” return −1 e l i f n == 0: return 1 else : return n ∗ f a c t o r i a l (n−1)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 57 / 60

slide-72
SLIDE 72

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Fibonacci

fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n-1) + fibonacci(n-2);

def fibonacci ( n ) : i f type ( n ) != type (1) : print ” Fibonacci i s

  • nly

defined f o r integers . ” return −1 e l i f n < 0: print ” Fibonacci i s

  • nly

defined f o r p o s i t i v e integers . ” return −1 e l i f n <= 1: return 1 else : return fibonacci (n−1) + fibonacci (n−2)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 58 / 60

slide-73
SLIDE 73

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Fibonacci

fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n-1) + fibonacci(n-2);

def fibonacci ( n ) : i f type ( n ) != type (1) : print ” Fibonacci i s

  • nly

defined f o r integers . ” return −1 e l i f n < 0: print ” Fibonacci i s

  • nly

defined f o r p o s i t i v e integers . ” return −1 e l i f n <= 1: return 1 else : return fibonacci (n−1) + fibonacci (n−2)

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 58 / 60

slide-74
SLIDE 74

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Glossary

modulus operator body base case boolean value branch infinite recursion boolean expression chained conditional tail recursion comparison operator nesting dead code logical operator recursion

None

conditional statement typing incremental development condition scope scaffolding block recursive call guardian

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 59 / 60

slide-75
SLIDE 75

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Exercise

x = 7 def scopetest ( param ) : x = param print x i f x == 0: return ” yes ” e l i f ( x % 2) == 0: x = param / 2 − 1 scopetest ( x ) else : x = x + 1 scopetest ( x ) scopetest ( x )

✡ ✝ ✆ ✞

7 8 3 4 1 2

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 60 / 60

slide-76
SLIDE 76

Conditionals More on Functions Recursion Examples The Nature of the Beast Stack and Traces

Exercise

x = 7 def scopetest ( param ) : x = param print x i f x == 0: return ” yes ” e l i f ( x % 2) == 0: x = param / 2 − 1 scopetest ( x ) else : x = x + 1 scopetest ( x ) scopetest ( x )

✡ ✝ ✆ ✞

7 8 3 4 1 2

✡ ✝ ✆

Lecture D.2. (MDV) Programming I Academic Year 2012-2013 60 / 60