COSC 1306 COMPUTER SCIENCE AND PROGRAMMING JehanFranois Pris

  • Slides: 49
Download presentation
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris jfparis@uh. edu Fall 2016

COSC 1306 COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris jfparis@uh. edu Fall 2016

THE ONLINE BOOK CHAPTER VI FUNCTIONS

THE ONLINE BOOK CHAPTER VI FUNCTIONS

Motivation n The for loop let us identify segments of code that are used

Motivation n The for loop let us identify segments of code that are used again and again ¨ Replace them with functions n Can also use functions to break down big programs into more manageable chunks

Example Program has 260 lines # START MAIN PROGRAM readinputs() # MAIN LOOP while

Example Program has 260 lines # START MAIN PROGRAM readinputs() # MAIN LOOP while eventlist != [] : [time, event, pid] = eventlist. pop(0) if event == 'ARRIVAL' : arrival(pid) elif event == 'CORE' : corecompletion(pid) elif event == 'DISK' : diskcompletion(pid) elif event == 'I/O' : iocompletion(pid) else : print("PANIC" ) # PRINT SUMMARY printsummary()

Functions n n n Straight extension of mathematical functions ¨ sin(…), cos(…), exp(…) Also

Functions n n n Straight extension of mathematical functions ¨ sin(…), cos(…), exp(…) Also apply to strings, lists, … Can be ¨ Built-in ¨ Imported from a Python module n import math y = math. sqrt(x) ¨ User defined

Writing your own functions n n def function_name(argument(s)) : statements Note ¨ The column

Writing your own functions n n def function_name(argument(s)) : statements Note ¨ The column at the end of the first line ¨ The indenting

An example def mysqrt(number) : root = number/2 for i in range(10) : inverse

An example def mysqrt(number) : root = number/2 for i in range(10) : inverse = number/root = (root + inverse)/2 return root

A very simple function def increment(number) : return number + 1 print("increment(5)", increment(5)) n

A very simple function def increment(number) : return number + 1 print("increment(5)", increment(5)) n Note that the print() statement is not part of the function n Many people prefer to leave an empty line after each function declaration

Back to turtles (I) import turtle def draw_square(t, sz): """Make t draw a sz

Back to turtles (I) import turtle def draw_square(t, sz): """Make t draw a sz by sz square. """ for i in range(4): t. forward(sz) t. left(90)

Back to turtles (II) wn = turtle. Screen() wn. bgcolor("lightgreen") wn. title("Alex meets a

Back to turtles (II) wn = turtle. Screen() wn. bgcolor("lightgreen") wn. title("Alex meets a function") # New alex = turtle. Turtle() draw_square(alex, 50) # Call draw_square wn. mainloop()

A more general function def draw_rectangle(t, w, h): """Get turtle t to draw a

A more general function def draw_rectangle(t, w, h): """Get turtle t to draw a rectangle of width w and height h. """ for i in range(2) : t. forward(w) t. left(90) t. forward(h) t. left(90)

A new draw_square function def draw_square(tx, sz): draw_rectangle(tx, sz) n n If we have

A new draw_square function def draw_square(tx, sz): draw_rectangle(tx, sz) n n If we have to draw rectangles and squares ¨ Write most general of the two ¨ Make the other a special case of the first Avoids doing the work twice

Flow of control (I) n When Python encounters a function definition ¨ It does

Flow of control (I) n When Python encounters a function definition ¨ It does not do anything with code ¨ It just remembers that the programmer defined that function n When Python encounters a function call ¨ It looks if the function was defined in an imported module or in the program ¨ It then executes that function

Flow of control (II) n Think of function declarations as specifying something the program

Flow of control (II) n Think of function declarations as specifying something the program can do n Put them ahead of the first place where they will be used: n Included modules n Function declarations n "Main" program

Function parameters n n Most functions have parameters ¨ Makes them more general mysqrt(number),

Function parameters n n Most functions have parameters ¨ Makes them more general mysqrt(number), draw_square(t, sz), draw_rectangle(t, w, h)

Functions returning a value n Some functions return values ¨ mysqrt(number) n Some do

Functions returning a value n Some functions return values ¨ mysqrt(number) n Some do not ¨ draw_square(t, sz), ¨ draw_rectangle(t, w, h)

What happens inside a function def mysqrt(number) : root = number/2 for i in

What happens inside a function def mysqrt(number) : root = number/2 for i in range(10) : inverse = number/root = (root + inverse)/2 return root i = 0 rt 2 =mysqrt(2. 0)

The question n n Have two variables with the same name ¨ In the

The question n n Have two variables with the same name ¨ In the main program ¨ In the function definition What will happen to the i variable in the main program when we call mysqrt()? ¨ Will it be set to 9? ¨ Will it remain equal to zero?

The answer n What happens in a function declaration ¨ … remains in the

The answer n What happens in a function declaration ¨ … remains in the function declaration n All variables used in a function declaration ¨ Are newly created variables ¨ Exist only inside the function body

What happens inside a function def mysqrt(number) : root = number/2 Use the for

What happens inside a function def mysqrt(number) : root = number/2 Use the for i in range(10) : green i inverse = number/root = (root + inverse)/2 here return root i = 0 rt 2 =mysqrt(2. 0). . . Use the red i here

Main advantage n Can use any variable name inside a function declaration n No

Main advantage n Can use any variable name inside a function declaration n No need to worry whether the name is used elsewhere

Organizing our code (I) def make_window(colr, ttle): """Set up a new window. """ w

Organizing our code (I) def make_window(colr, ttle): """Set up a new window. """ w = turtle. Screen() w. bgcolor(colr) w. title(ttle) return w

Organizing our code (II) def make_turtle(colr, sz): """ Set up a new turtle. """

Organizing our code (II) def make_turtle(colr, sz): """ Set up a new turtle. """ t = turtle. Turtle() t. color(colr) t. pensize(sz) return t

Organizing our code (III) wn = make_window("lightgreen", "Tess and Alex dancing") tess = make_turtle("hotpink",

Organizing our code (III) wn = make_window("lightgreen", "Tess and Alex dancing") tess = make_turtle("hotpink", 5) alex = make_turtle("black", 1) dave = make_turtle("yellow", 2) Our main program is shorter and easier to understand

The accumulator pattern n Suppose we want to count the sum of the first

The accumulator pattern n Suppose we want to count the sum of the first n numbers ¨ def sum_them_all(n) : running_total = 0 # before the loop for i in range(1, n + 1) : running_total += i return running_total #after it

The accumulator pattern n Suppose we want to count the sum of the first

The accumulator pattern n Suppose we want to count the sum of the first n numbers ¨ def sum_them_all(n) : running_total = 0 # before the loop for i in range(1, n + 1) : running_total += i return running_total #after it

Python will refuse to execute ¨ def sum_them_all(n) : for i in range(1, n

Python will refuse to execute ¨ def sum_them_all(n) : for i in range(1, n + 1) : running_total += i return running_total #after it

Will return n ¨ def sum_them_all(n) : for i in range(1, n + 1)

Will return n ¨ def sum_them_all(n) : for i in range(1, n + 1) : running_total = 0 # WRONG running_total += i return running_total #after it

Will return 1 ¨ def sum_them_all(n) : running_total = 0 # before the loop

Will return 1 ¨ def sum_them_all(n) : running_total = 0 # before the loop for i in range(1, n + 1) : running_total += i return running_total # WRONG

Functions can call functions n Recall ¨ def draw_square(tx, sz): draw_rectangle(tx, sz)

Functions can call functions n Recall ¨ def draw_square(tx, sz): draw_rectangle(tx, sz)

The main function n n Unlike C and C++, Python has no notion of

The main function n n Unlike C and C++, Python has no notion of a specian main function If you try ¨ def main() : print("Hello World") nothing will happen ¨ Python will define a main() function but not execute it

A personal comment n You will have to learn the little peculiarities of each

A personal comment n You will have to learn the little peculiarities of each language n In French, I would not say ¨ My name is Jehan-François but instead the equivalent of ¨ *I call myself Jehan-François

Stepwise refinement n Suppose we are asked to draw the front of a house

Stepwise refinement n Suppose we are asked to draw the front of a house with a flat roof n How should we proceed?

Step one n draw_frame(turtle, width, height, color) draw_windows(? ? ? ) position(turtle, x, y)

Step one n draw_frame(turtle, width, height, color) draw_windows(? ? ? ) position(turtle, x, y) draw_door(turtle, width, height, color, doorknob_color, doorknob_side)

The easiest draw_frame(trtl, w, h, clr) : draw_filled_rectangle(trtl, w, h, clr) which will use

The easiest draw_frame(trtl, w, h, clr) : draw_filled_rectangle(trtl, w, h, clr) which will use n draw_filled_rectangle(trtl, w, h, clr) : trtl. fillcolor(clr) trtl. start_fill() draw_rectangle(trtl, w, h) trtl. end_fill n

The door n n draw_door(trtl, w, h, clr, dk_clr, dk_side) : draw_filled_rectangle(trtl, w, h,

The door n n draw_door(trtl, w, h, clr, dk_clr, dk_side) : draw_filled_rectangle(trtl, w, h, clr) // must learn to make choices: // left or right position_doorknob(? ? ? ) // Does not work OMG !!!

The door revisited n draw_door(trtl, x, y, w, h, clr, dk_clr, dk_side) : position(trtl,

The door revisited n draw_door(trtl, x, y, w, h, clr, dk_clr, dk_side) : position(trtl, x, y) draw_filled_rectangle(trtl, w, h, clr) // assume knob on right side dk_x =x + w*9/10 // BAD dk_y= y + h/2 position turtle(trtl, dk_x, dk_y) draw_filled_circle(trtl, dk, clr)

The windows n n Replace ¨ draw_windows(? ? ? ) by ¨ position(trtl, x

The windows n n Replace ¨ draw_windows(? ? ? ) by ¨ position(trtl, x 1, y 1) draw_window(w, h, clr) position(trtl, x 2, y 2) draw_window(w, h, clr) position(trtl, x 3, w 3) draw_window(w, h, clr) Will have problems drawing the window frames!

The windows n n Use ¨ draw_window(trtl, w, h, clr) position(trtl, x 2, y

The windows n n Use ¨ draw_window(trtl, w, h, clr) position(trtl, x 2, y 2) draw_window(w, h, clr) position(trtl, x 3, w 3) draw_window(w, h, clr) Will have problems drawing the window frames!

A turtle bar chart (I)

A turtle bar chart (I)

A turtle bar chart (II) import turtle

A turtle bar chart (II) import turtle

A turtle bar chart (III) # def draw. Bar(t, height): """ Get t to

A turtle bar chart (III) # def draw. Bar(t, height): """ Get t to draw one bar of height. """ t. begin_fill() # start filling t. left(90) # up t. forward(height) t. write(str(height)) # write label t. right(90) # back to horizontal t. forward(40) t. right(90) #down t. forward(height) t. left(90) t. end_fill() # stop filling

A turtle bar chart (IV) xs = [48, 117, 200, 240, 160, 220] #

A turtle bar chart (IV) xs = [48, 117, 200, 240, 160, 220] # here are the data to plot maxheight = max(xs) # max entry in list numbars = len(xs) # size of list border = 10 # extra space top and right

A turtle bar chart (V) # Set up the window and its attributes wn

A turtle bar chart (V) # Set up the window and its attributes wn = turtle. Screen() wn. setworldcoordinates(0 -border, 40*numbars+border, maxheight+border) # do not study this wn. bgcolor("lightgreen")

setworldcoordinates() n setworldcoordinates(llx, lly, urx, ury) ¨ Four numbers n llx : x-coordinate of

setworldcoordinates() n setworldcoordinates(llx, lly, urx, ury) ¨ Four numbers n llx : x-coordinate of lower left corner of canvas n lly : y-coordinate of lower left corner of canvas n urx : x-coordinate of upper right corner of canvas n ury: y-coordinate of upper right corner of canvas

A turtle bar chart (VI) # Setup turtle tess = turtle. Turtle() tess. color("blue")

A turtle bar chart (VI) # Setup turtle tess = turtle. Turtle() tess. color("blue") tess. fillcolor("red") tess. pensize(3)

A turtle bar chart (VII) # draw the chart for a in xs: draw.

A turtle bar chart (VII) # draw the chart for a in xs: draw. Bar(tess, a) # works because tess is always where # it should be after having drawn # a bar wn. exitonclick()

There is more n There are many other aspects of functions that are left

There is more n There are many other aspects of functions that are left to be discovered later ¨ Optional parameters ¨ Parameters with default values ¨ Declaring some variables to be global ¨… n Python is like a big city that takes time to discover