CMPT 120 - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

CMPT 120

Description:

'Instructions for cooking Chicken Chasseur''' title = 'How to Cook Chicken Chasseur' ... can refer to a non-local (global) variable, as long as it does not have the ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 24
Provided by: johne78
Category:
Tags: cmpt | chicken | cook | does | how | long | need | to

less

Transcript and Presenter's Notes

Title: CMPT 120


1
CMPT 120
  • Functions

2
Objectives
  • Define and use functions
  • Understand the concept of variable scope

3
What is a Function?
  • A self contained set of instructions
  • Excerpt from Katie Stewarts Cookbook
  • Add the brandy to the frying pan and set
    alight shake pan gently so flames spread over
    the contents of the pan. Flaming burns off
    excess fat and gently adds to the flavour of the
    dish. When flames go out, add the mushrooms,
    tomato puree and white wine. Boil the sauce,
    stirring occasionally, for at least 5 minutes to
    reduce and concentrate the flavour. Add the
    prepared brown sauce and heat through. Check
  • add the prepared brown sauce to find out how to
    prepare Brown Sauce we need to follow a separate
    recipe (on page 154).

4
Function Introduction
  • Python has many built in functions
  • len, raw_input, dir etc.
  • There are many modules that contain functions
  • math
  • turtle
  • random
  • There are also functions that belong to some
    object (called methods)
  • e.g. String functions, count, append, upper and
    so on

5
Calling Functions
  • Using a function is referred to as calling or
    invoking the function
  • Whenever a function is called it must be followed
    by brackets ()
  • The brackets contain input to the function
  • Values given as input to a function are referred
    to as arguments
  • Even when a function doesnt need input empty
    brackets are still required

6
Return Values
  • Some functions return values
  • The function performs some operation(s) and
    produces a result
  • The result is then returned to the calling
    statement
  • Return values are often assigned to a variable
  • e.g. length len("how long am I")

input to function (its argument)
assigns return value to length
7
How Functions Work
  • When a function is called, execution switches to
    it and any arguments to it are copied to its
    parameters
  • The function body statements are executed
  • Its as if the statements in the body of the
    function were inserted into the calling program
  • The execution of the function ends when
  • The last line of its body is executed or
  • A return statement is reached (in which case a
    value is returned to the calling code)
  • The calling code continues where it left off

8
Function Anatomy
  • def chicken_chasseur()

colon
function requires no input
function name
keyword to define a function
9
Function Anatomy
  • def chicken_chasseur()
  • """Instructions for cooking Chicken Chasseur"""

Documentation string - this can be seen by typing
the function name followed by .__doc__ e.g.
chicken_chasseur.__doc__ To make the purpose of
a function clear it often helps to give examples.
10
Function Anatomy
  • def chicken_chasseur()
  • """Instructions for cooking Chicken Chasseur"""
  • title 'How to Cook Chicken Chasseur'
  • print title
  • print len(title) '-'
  • print '1 Buy chicken'
  • print '2 Buy cook book'
  • print '3 Look up Chicken Chasseur recipe in
    book'
  • print '4 Follow instructions carefully '

function body - the function call ends when the
last line has been executed
11
Function Components
  • Function header or signature
  • Keyword def
  • Function name (which should indicate the
    functions purpose)
  • Function parameter list (inputs for the
    function), if required
  • Colon
  • Function body
  • The statements to be executed by the function
    including
  • A documentation string on the first line of the
    function
  • Must be indented (like all Python body
    statements)
  • Optional return statement

12
Printing My Name in a Box
  • Here is a function that prints my name in a fancy
    box
  • def print_name_in_box()
  • """Prints "John Edgar" in an asterisk box"""
  • middle " John Edgar "
  • asterisks '' len(middle)
  • print asterisks
  • print middle
  • print asterisks
  • And here is a program that uses it
  • print "This is my name"
  • print_name_in_box()
  • print "wow!"

This is my name John Edgar
wow!
13
Inputting Data to a Function
  • Many functions require input
  • e.g. len needs something to measure the length of
  • Other functions can be made more useful by giving
    them input
  • e.g. a function to print any string in an
    asterisk box is more useful than one that just
    prints my name
  • When a function is defined the data it requires
    should be specified in its parameter list

14
Function Parameters
  • The list of values required for a function is
    called a parameter list
  • The parameter list is part of the function header
  • Parameters can be of any type
  • The parameters are given the values passed to the
    function when it is called
  • Parameters can be used in the function in the
    same way that variables are used
  • i.e. the parameter names can be referred to in
    the function body to access their values

15
Function Input Errors
  • Calling a function without giving it the required
    input results in an error. i.e.
  • Giving a function data where no data is required
  • Not giving a function data where data is required
  • Giving a function data of the wrong type
  • Giving a function with multiple parameters the
    right data in the wrong order

16
Function Arguments
  • Here is a more general version of the name
    printing function
  • def print_string_in_box(str)
  • """Prints str in an asterisk box"""
  • middle ' ' str ' '
  • asterisks '' len(middle)
  • print asterisks
  • print middle
  • print asterisks
  • And here is a program that uses it
  • user_name raw_input("What is your name? ")
  • print "This is my name"
  • print_string_in_box(user_name)

17
Argument and Parameter Names
  • Notice how the name of the parameter of
    print_string_in_box was different from the name
    of the variable passed to it
  • The parameter was called str
  • The argument was called user_name
  • When the function was called, the parameter str
    was given the value of user_name
  • Note it is actually slightly more complicated
    than that!

18
Returning Values
  • Some functions return values
  • len returns the length of the argument passed to
    it
  • e.g. len("Hello") returns the value 5
  • The function body produces some value (an integer
    in the case of len) and sends this value back to
    the calling code
  • Known as returning a value
  • The returned value can then be used outside the
    body of the function

19
Using Returned Values
  • A value that is returned from a function can be
    used anywhere that a value of that type can be
    used
  • A return value can be assigned to a variable
  • word_length len("Hello")
  • A return value can be printed
  • print "Hello has", len("Hello"), "characters"
  • A return value can be passed to a function
  • min(len("Hello"), len("Hi"))

20
Defining Return Values
  • To make a function return a value use the return
    statement
  • e.g. return result
  • A function stops executing and returns control to
    the calling code once it reaches a return
    statement
  • The returned value is then substituted into the
    program where the function was called
  • A function can have multiple return statements,
    e.g. in an if, elif, , elif, else statement

21
return Example
  • def longest_string(str1, str2)
  • """Returns the length of the longest of two
    strings"""
  • len1 len(str1)
  • len2 len(str2)
  • if (len1 gt len2)
  • return len1
  • else
  • return len2
  • (much) shorter version
  • def longest_string_v2(str1, str2)
  • """Returns the length of the longest of two
    strings"""
  • return max(len(str1), len(str2))

22
Variable Scope
  • A variable that is declared within a function can
    only be used inside that function and only exists
    inside the function
  • This applies to parameters as well
  • The variable or parameters scope is local to the
    function
  • The variable or parameter only exists during the
    functions exectution - it has the same lifetime
    as the function
  • Think of functions as black boxes that the
    calling program cannot see inside
  • A function can refer to a non-local (global)
    variable, as long as it does not have the same
    name as a locally declared variable
  • However, it is generally good practice not to
    refer to program variables (global variables)
    inside a function

23
Variables With the Same Name
  • What happens when a variable declared inside a
    function has the same name as another variable
    declared outside the function?
  • During the lifetime of the function there are two
    variables which point to separate memory
    addresses but which have the same name
  • The function variable is used inside the function
  • The global variable is used outside the function
    and cannot be accessed inside the function
Write a Comment
User Comments (0)
About PowerShow.com