Functions and subroutines - PowerPoint PPT Presentation

About This Presentation
Title:

Functions and subroutines

Description:

Functions and subroutines 01204111 Computer and Programming – PowerPoint PPT presentation

Number of Views:140
Avg rating:3.0/5.0
Slides: 38
Provided by: acth
Category:

less

Transcript and Presenter's Notes

Title: Functions and subroutines


1
Functions and subroutines
  • 01204111 Computer and Programming

2
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 Corner
  • Let's recall the functions that we have been
    using so far. Think about their goals, their
    inputs, and their outputs.

functions inputs 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-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 of a triangle
  • Write a program that reads the length of the base
    and the height of a triangle and computes its
    area.

Read the base length
Read the height
Read the length of the base and the height of a
triangle and compute its area
Compute the area
Dividedintosmallertasks
Report the result
6
Major plan
Read the base length
Read the height
b read_base() h read_height() a
compute_area(b,h) show_area(a)
Compute the area
Report the result
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.5baseheight 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 function in Python
def function_name(parameters)
sequence of statements return value
(if any)
Add the same indentation to show the block
  • 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.

9
Parameters
  • 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
    functionessential 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.5baseheight
compute_area(32,80)
base
32
height
80
10
Let's look closely at the definition
def compute_area(base,height) return
0.5baseheight
  • 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

11
Thinking 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)
12
Notes
  • The statements inside the function definition
    will not be executed inside the definition. They
    will be executed when the function is called.

This "print" runs immediately.
gtgtgt print("Hello") Hello gtgtgt def func() ...
print("hi") gtgtgt gtgtgt func() Hi gtgtgt
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 flow
1. This "print" is not belongs to any function
therefore, it is executed normally.
print("Hello") def func1() print("hi") def
func2() print("bye") func1() func2() func1()
1
2. Python see the "def " statements therefore,
it remembers the definitions of func1 and func2
both print functions shall not be executed here.
2
3. This is a call to func1. Now, the program
execution jumps to the definition of function
func1.
3
4
4. This is a call to func2. The program
execution then jumps to the definition of
function func2.
5
5. Same as 3
14
Example the turtle houses (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

15
Example the turtle houses (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 to draw walls
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)
  • 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.

17
Teach the turtle to draw the roof
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!
  • 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,siz
e)
19
Full program
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,s
ize) build_roof(turtle,size) t
Turtle() build_house(t,300) try to build a
house
20
Experimenter's Corner
  • 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...
  • 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 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 centimeters to inches
  • 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 cm

def cm_to_inch(x) return x/2.54
24
How to test functions in Wing IDE
1. Start a new program
3. Save the file
4. Hit "Run"
2. Enter function definition
5. Experiment with the function
25
Thinking Corner inches 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 centimeters to feet
  • 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

gtgtgt inch_to_foot(cm_to_inch(250)) 8.20209973753280
9
Length in cm
Length in inches
Length in feet
cm_to_inch
inch_to_foot
27
Thinking Corner cm 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 Computing moving distance
  • 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 volume of cylinders
  • Define function volume, which
  • Takes two parameters
  • r, the radius of the base
  • h, the height of the cylinder
  • Returns the volume of the cylinderwhose base
    radius is r and height is h.

30
Thinking Corner When will the bucket 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
Example
Enter tank's diameter (inch) 12 Enter tank's
height (inch) 3 Enter water flow rate (cc/s)
15 Time to fill the tank is 6.17777758516 minutes
32
Side notes formatting strings with
  • We can format the output using operator
  • Try to change the previous program to show the
    duration with only two decimal digits.

Put the value of x with 2 decimal digits here
gtgtgt x 8.3 gtgtgt 'Time to fill the tank is .2f
minutes' x 'Time to fill the tank is 8.30
minutes' gtgtgt print("Time to fill the tank is .2f
minutes" x) Time to fill the tank is 8.30
minutes
33
Scope 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 variables
This variable y is a different variable from the
one defined outside.
x 8 y 3 def myfunc() y 5 a
x myfunc() print(x,y)
This variable x is the same variable as the one
outside
The output from function print is "8 3", That is,
the global variable y remains unchange.
35
But be careful
x 8 def myfunc() print(x) myfunc()
Varible x here is the same as the global one
  • Result the program prints 8
  • Result Python shows errors

This assignment makes variable x in myfunc to be
local.
x 8 def myfunc() print(x) x
3 myfunc()
Therefore, this x (which is the same x as in the
next line) refer to a local variable which does
not exist.
36
Global 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)
Now, this y is the same as the one outside
The result is then 8 5
37
Suggestions
  • 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.
Write a Comment
User Comments (0)
About PowerShow.com