Functions and subroutines 01204111 – Computer and Programming.

37
Functions and Functions and subroutines subroutines 01204111 – Computer and Programming

Transcript of Functions and subroutines 01204111 – Computer and Programming.

Functions and Functions and subroutinessubroutines

01204111 – Computer and Programming

2

Do you know…Do you know…•None of the programming

languages can provide all the specific commands that developers need.

•But many languages provide supports for user-defined commands, in the form of

Functions

3

Thinking CornerThinking Corner•Let's recall the functions that

we have been using so far. Think about their goals, their inputs, and their outputs.funct

ionsinputs goals outputs

print Any expressions

Shows the value of the expression to the console

-

input A string or none

Reads input from the user

The input as a string

int A string or a number

Converts the argument to an integer

An integer

float A string or a number

Converts the argument to a floating-point number

A floating-point

4

Why build user-Why build user-defined functions?defined functions?•This is a way to handle

complexity of the problems: reduce a big task to many smaller ones.

•Reduce duplicate codes For simpler maintainance

•Reduce the complexity of the main program This makes it easier to read

5

Example: the area Example: the area of a triangleof a triangle

•Write a program that reads the length of the base and the height of a triangle and computes its area.

Read the length of the base and the

height of a triangle and compute its area

Read the base length

Read the height

Compute the area

Report the result

Dividedinto

smallertasks

6

Major planMajor plan

Read the base length

Read the height

Compute the area

Report the result

b = read_base()h = read_height()a = compute_area(b,h)show_area(a)

b = read_base()h = read_height()a = compute_area(b,h)show_area(a)

7

โปรแกรมที่�สมบู�รณ์�โปรแกรมที่�สมบู�รณ์�def read_base(): b = input("Enter base: ") return int(b)

def read_height(): h = input("Enter height: ") return int(h)

def compute_area(base,height): return 0.5*base*height

def show_area(area): print("Triangle area is", area)

b = read_base()h = read_height()a = compute_area(b,h)show_area(a)

def read_base(): b = input("Enter base: ") return int(b)

def read_height(): h = input("Enter height: ") return int(h)

def compute_area(base,height): return 0.5*base*height

def show_area(area): print("Triangle area is", area)

b = read_base()h = read_height()a = compute_area(b,h)show_area(a)

8

Defining a Defining a function in Pythonfunction in Python

•Parameters are optional. If a function needs more information, then parameters are required.

•Functions that have no return values do not need the return statement.

def function_name(parameters…): : sequence of statements : return value (if any)

def function_name(parameters…): : sequence of statements : return value (if any)Add the same

indentation to show the

block

9

ParametersParameters• A function can take more information. On

its definition, we can list all parameters that it needs

Inside the function, parameters are variables that are initialized when the function is called. Thus the statement below that calls the function

essential creates variables base and height that refer to 32 and 80 respectively.

These variables no longer exist after the function execution ends.

def compute_area(base, height): return 0.5*base*height

def compute_area(base, height): return 0.5*base*height

compute_area(32,80)compute_area(32,80)

base 32 height 80

10

Let's look closely Let's look closely at the definitionat the definition

•Function name: compute_area•Goal:

Compute the area of a triangle from the length of its base and its height.

•Parameters: The base length, in parameter base The height, in parameter height

•Return value: The area of the triangle

def compute_area(base,height): return 0.5*base*height

def compute_area(base,height): return 0.5*base*height

11

Thinking CornerThinking Corner•Consider other functions on

the previous example. Try to figure out various information of the them as in the previous slide. Function names? Goals? Parameters? Return values?

def read_base(): :def read_height(): :def compute_area(base,height): :def show_area(area): :

def read_base(): :def read_height(): :def compute_area(base,height): :def show_area(area): :

12

NotesNotes•The statements inside the

function definition will not be executed inside the definition. They will be executed when the function is called.

>>> print("Hello")Hello>>> def func():... print("hi")>>>>>> func()Hi>>>

>>> print("Hello")Hello>>> def func():... print("hi")>>>>>> func()Hi>>>

This "print" runs immediately.This "print" will not be

executed here, because it is in

the function definition.

But when the function

is called, the second

"print" statement

is executed.

13

Program flowProgram flowprint("Hello")

def func1(): print("hi")

def func2(): print("bye")

func1()func2()func1()

print("Hello")

def func1(): print("hi")

def func2(): print("bye")

func1()func2()func1()

1

2

3

4

5

1. This "print" is not belongs to any function; therefore, it is executed normally.2. Python see the "def " statements; therefore, it remembers the definitions of func1 and func2; both print functions shall not be executed here.3. This is a call to func1. Now, the program execution jumps to the definition of function func1.4. This is a call to func2. The program execution then jumps to the definition of function func2.5. Same as 3

14

Example: the Example: the turtle & houses turtle & houses

(1)(1)•We want to build a function build_house that asks the turtle to draw a house of a specific size.

•The function needs to parameters turtle, for the turtle that will draw

size, for the size of the house

size

size

size

15

Example: the Example: the turtle & housesturtle & houses

(2)(2)•After some analysis, we see that to build a house, we need to subtasks: Build the walls Build the roof

•Therefore, we shall need two other functions: build_walls --- for building walls build_roof --- for building the roofs

•These functions shall be called by function build_house.

16

Teach the turtle Teach the turtle to draw wallsto draw walls

•Note that we make sure that the direction of the turtle remains the same from the start. This is for the ease of designing the build_roof function later on.

def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90)

def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90)

size

size

17

Teach the turtle Teach the turtle to draw the roofto draw the roofdef build_roof(turtle,size): # Since we know the turtle is facing right # we can tell the turtle to turn left # for drawing an equilateral triangle turtle.left(60)

# and draw it turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size)

# finally, we ask the turtle to return # to its starting direction turtle.right(180)

def build_roof(turtle,size): # Since we know the turtle is facing right # we can tell the turtle to turn left # for drawing an equilateral triangle turtle.left(60)

# and draw it turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size)

# finally, we ask the turtle to return # to its starting direction turtle.right(180)

size

18

Finally, the house!Finally, the house!•After we can draw the walls

and the roof, we can easily teach the turtle to draw houses.def build_house(turtle,size):

build_walls(turtle,size) build_roof(turtle,size)

def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size)

19

Full programFull programfrom turtle import *

def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90)

def build_roof(turtle,size): turtle.left(60) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(180)

def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size)

t = Turtle()build_house(t,300) # try to build a house

from turtle import *

def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90)

def build_roof(turtle,size): turtle.left(60) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(180)

def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size)

t = Turtle()build_house(t,300) # try to build a house

20

Experimenter's Experimenter's CornerCorner

•From the turtle program Try to swap statement build_roof and build_walls in function build_house. Is the result the same?

Try to change the direction of the turtle before calling build_house. How is the result?

21

Side notes...Side notes...•The terms used to call "function" in

other programming languages may be different In Object-oriented languages like C# or Java, a function is called a method.

Functions that do not return values may be called subroutines or procedures.

•Parts of a program which do not belong to any function is usually called "main program" Languages, such as C, C#, and Java, require programmers to write main program in under a specific function, e.g., function main.

22

Thinking CornerThinking Corner•Change the main program so

that the turtle draws 3 houses (same size) with space of size 30 between two consecutive houses.

20

23

Example: from Example: from centimeters to centimeters to

inchesinches•Define function cm_to_inch Takes one parameter, a length in centimeters.

Returns the same length in inches.

Use the following rule: 1 inch = 2.54 cmdef cm_to_inch(x):

return x/2.54

def cm_to_inch(x): return x/2.54

24

How to test How to test functions infunctions in Wing Wing

IDEIDE1. Start a new program

2. Enter function definition

3. Save the file

4. Hit "Run"

5. Experiment with the function

25

Thinking Corner: Thinking Corner: inches to feetinches to feet

•Define function inch_to_foot, which Takes one parameter, the length in inches.

Returns the length in feet 1 foot = 12 inches

26

Example: Example: centimeters to centimeters to

feetfeet• The function calls that return values can be used as expressions.

• This kind of expressions can be used in other expressions or even as arguments to other function calls

>>> inch_to_foot(cm_to_inch(250))8.202099737532809

>>> inch_to_foot(cm_to_inch(250))8.202099737532809

cm_to_inch inch_to_foot

Length in cm Length in inches Length in feet

27

Thinking Corner: Thinking Corner: cm to footcm to foot

•Define function cm_to_foot It is required that this function must use function cm_to_inch and function inch_to_foot defined previously.

28

Thinking Corner: Thinking Corner: Computing moving Computing moving

distancedistance•Take the example from last time that computes the distance from the acceleration and the duration and write it as a function Function name: distance Takes two parameters:

a (acceleration in m/s2), and t (duration in seconds)

Returns the distance that the object, initially staying still, moves.

29

Thinking Corner: Thinking Corner: volume of cylindersvolume of cylinders

•Define function volume, which Takes two parameters

r, the radius of the baseh, the height of the cylinder

Returns the volume of the cylinderwhose base radius is r and height is h.

hhr

v = r2 x h

30

Thinking Corner: Thinking Corner: When will the When will the bucket be fullbucket be full??• We are filling a bucket with water.

• Write a program that computes the duration needed to fill the full bucket, whose shape is a cylinder.

• The program should read from the user: The diameter of the bucket, in inches The height of the bucket, in inches The rate of the water flowing into

the bucket, in cc/s• Then shows the duration needed to fill

the bucket in minutes.

31

ExampleExampleEnter tank's diameter (inch): 12Enter tank's height (inch): 3Enter water flow rate (cc/s): 15Time to fill the tank is 6.17777758516 minutes

Enter tank's diameter (inch): 12Enter tank's height (inch): 3Enter water flow rate (cc/s): 15Time to fill the tank is 6.17777758516 minutes

32

Side notes: Side notes: formatting strings formatting strings

withwith %%•We can format the output using operator %

•Try to change the previous program to show the duration with only two decimal digits.

>>> x = 8.3>>> 'Time to fill the tank is %.2f minutes' % x'Time to fill the tank is 8.30 minutes'>>> print("Time to fill the tank is %.2f minutes" % x)Time to fill the tank is 8.30 minutes

>>> x = 8.3>>> 'Time to fill the tank is %.2f minutes' % x'Time to fill the tank is 8.30 minutes'>>> print("Time to fill the tank is %.2f minutes" % x)Time to fill the tank is 8.30 minutes

Put the value of x with 2 decimal digits here

33

Scope of variablesScope of variables•The scope of variables defined inside a

function starts from the point of the definition and ends where the function ends These variables are called local variables.

•The scope of variables defined outside any functions starts from the point of the definition and ends at the end of the program. These variables are called global variables.

34

Local and global Local and global variablesvariables

x = 8y = 3

def myfunc(): y = 5 a = x

myfunc()print(x,y)

x = 8y = 3

def myfunc(): y = 5 a = x

myfunc()print(x,y)

This variable y is a different variable from the

one defined outside.

This variable x is

the same variable as

the one outsideThe output from

function print is "8 3",

That is, the global variable y remains

unchange.

35

But be carefulBut be careful

• Result: the program prints 8

• Result: Python shows errors

x = 8

def myfunc(): print(x)

myfunc()

x = 8

def myfunc(): print(x)

myfunc()

x = 8

def myfunc(): print(x) x = 3

myfunc()

x = 8

def myfunc(): print(x) x = 3

myfunc()

This assignment

makes variable x in myfunc to be

local.

Therefore, this x (which is the

same x as in the next line) refer to

a local variable which does not

exist.

Varible x here is the

same as the global one

36

GlobalGlobal statement statement•We can explicitly declare that

this variable is the same as the global one.x = 8

y = 3

def myfunc(): global y y = 5 a = x

myfunc()print(x,y)

x = 8y = 3

def myfunc(): global y y = 5 a = x

myfunc()print(x,y)

Now, this y is the same as the one

outside

The result is then 8 5

37

SuggestionsSuggestions•Try to avoid using global

variables, because In this case, the behavior of the function is not only determined by the parameters, but it also depends implicitly on the global variables.

This, in turns, make it very hard to understand the program when many functions can change the value of the global variables.