Download PPT

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CLINT-L
Functions
Functions
• It often happens that part of a program
needs to be used several times over
• Rather than repeating the same code
several times over, it is more efficient (and
reliable) to localize this work inside a
function.
• A function is a programming construct
which takes one or more inputs, and
produces an output.
How Functions are Used
Functions are used in two distinct ways.
• Function definition
This is where we specify what the function
actually dues
• Function call
This is where we actually invoke the
function
Very Simple Function Definition
def add1(n):
"""add 1 to n."""
return n+1
Anatomy of a Function Definition
• The keyword def introduces a function definition.
• It must be followed by
– the function name
– a parenthesized list of formal parameters. These
function as placeholders for passed values.
– a colon
– The statements that form the body of the function
start at the next line. These must be indented.
• The first statement of the function body can
optionally be a string literal; this string literal is
the function's documentation string, or docstring.
• The keyword return is used to return a value
Calling a function
>>> add1(2)
3
• Note that the function call has to match the
shape of the function defined.
• Actual parameters are used to pass information
to the function: in this case, the number 2.
• Actual parameters are evaluated and the values
are then transmitted to the function definition.
Exercise 3.1
• Write a function sum(x,y) that computes
the sum of two numbers.
• Write a function that computes the product
of two numbers using only the sum
function that you have just defined.
• Write a function that computes factorial(n).
factorial(4) = 4 x 3 x 2 x 1
• Write a function that computes the
average of a list of numbers.