functions part i (syntax). what is a function? a function is a set of statements which is split off...

31
Functions Part I (Syntax)

Upload: lester-phelps

Post on 29-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Functions Part I (Syntax)

Page 2: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

What is a function?

• A function is a set of statements which is split off into a separate entity that can be used like a “new keyword”• It has a name • It should have a specific task to do (functional cohesion)• It has a parameter list (data that it needs to work on for the task)• It is also called a subroutine, subprogram, procedure or module in

different languages

Page 3: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Why write code in functions?

• You can write the code once, use it many times• It’s easier to divide work among the members of a team – each one is

responsible for a certain function• You can put off the details when you are writing the top-level code of

the program “abstraction or generalization” and then later, focus on just one function at a time (top down design)• You can write the program incrementally, one function at a time

(bottom up design)• Testing is easier (unit testing)

Page 4: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Why write code in functions?

• You can think of a function as a ‘black box’ – you only know what goes into it and what should come out of it, not what is going on inside• This organization allows for easier changes of a function’s

implementation – the function code is all that has to change• Software companies often sell libraries of functions – they sell the

executable code and documentation of the headers of the functions, that is, the parameter lists and the value that is returned by the function – you don’t get to see the implementation, just the interface. Later the company may implement the function library in a more efficient way – they can send you the update without your having to change your code at all!

Page 5: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

A Black BoxYou can think of a function as a black box. Put certain things IN and certain things (or actions) come OUT.

The details of what’s in the box can be postponed for a while.

Black BoxInput Output

Page 6: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Syntax of functions – two parts

• A function has to have a definition• And a function needs to be called (otherwise it is not executed)

Page 7: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Syntax of a definition of a function

• Starts with def identifier (parameters): at left edge of screen• Statements follow the def line, indented one tab stop (the “body”)• When the lines stopped being indented, the function definition is finished• It may or may not end with a return statement• Parameter list can be empty or as many identifiers as desired with commas

between, parameters are not expressions or constants• Where the function definition is placed in the source file is up to you – the

main rule is that it must be defined before the first call to the function appears in the file• Functions can be defined inside other function definitions. This is generally not

necessary – please do not do this in this class

Page 8: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Syntax of function call (invocation)

• There are two kinds of calls to functions• If the function returns a value, the function call must be part of a statement –

it cannot stand alone• Example: y = sqrt(x)• Example: print(sqrt(x))• NOT correct: sqrt(x) # Python allows this to be written but it does

# nothing with the result of the function, so it’s a waste of time

• If the function does not return a value, the function call is a stand-alone statement• Example: win.close()• Example: circ1.setFill(“red”) # changes the object, does not return a value• Not correct: y = win.close() # y will get the value None

Page 9: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Functions Part 2 (Semantics)

Page 10: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Semantics of function definitions

• What happens when a function definition is encountered in a file that is being executed?• When the keyword def is encountered, Python makes a note of the

identifier following it, as a function name. All the lines that are indented (the ‘body’) after the def line are recorded as the function definition. The lines of the body are NOT executed at that time. They are simply recorded as part of that function. • If there are syntax errors in the function definition, they will NOT be

noted at that time

Page 11: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Semantics of a function call (invocation)1. The function which is doing the calling is paused – put on hold2. Copies of the argument values are put in the places where the parameters

are in the function definition code3. Execution starts with the start of the function definition and continues until

either a return statement is executed or the definition runs out of code – any local variables are created as needed

4. At the point of return, the copies of the arguments and any local variables created are destroyed

5. The return value (or None) is passed back to the function doing the calling6. The calling function picks up where it left off, using the return value

Page 12: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Scope and Lifespan of Identifiers

Page 13: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Every function has a scope

• What does that mean? • That means that every identifier that is created in a function (that’s

variables and function names) belongs to that function• The identifier is accessible (useable) in that function and nowhere

else, it is local to the function• This is the default behavior of variables (not just in Python)• It is a GOOD thing because it allows you to focus on solving the

problem that the function is supposed to solve, without worrying about what other functions used for names for their variables

Page 14: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Global variables

• The other scope that exists in a program file is “global”. This is an identifier which is defined outside of ALL function definitions• An identifier which is global can be accessed anywhere in the file, in any

function which appears below the definition of the identifier• Using Global variables is considered NOT good style – and are not allowed in this

class• Some people want to do it because they think it makes functions easier to write

– no parameter lists! Everything is global!• If parameter lists are very difficult for you, then you need to understand your

function’s purpose. If you cannot decide what needs to be a parameter, ask yourself “will the function get this info from outside, or will it generate it itself?”

Page 15: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Why global variables are bad style

• If you want to copy a function to use in another program, and the function uses a global variable, you must also copy the global variable definition• If you are working as part of a team on a program, if you create a

global variable, there is NO WAY to prevent other team members from using/changing your global – you have no way to control access• If you want a function to be general, you do NOT use global variables

– it is much more difficult to keep changing the global variable between calls than it is to call the function with different arguments• They make testing and debugging much harder!

Page 16: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Lifespan of a variable

• How long does a variable “live”? That is, when during the execution does a variable have memory and retain its value?• This is a dynamic way of thinking about variables, as opposed to

scope, which is more static• If you had to describe the scope of a variable, you could print out the

code of a program and circle the scope on the paper – it does not change• If you had to describe the lifespan of a variable, you would have to

describe when the variable was created and when it was destroyed, which varies depending on the execution of the program

Page 17: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Lifespans

• The lifespan of a variable local to a function is from the time it is created in the function’s run, until the function ends (and the memory allocated to the variable is released) It’s the same for parameters to that function also.• The lifespan of a global variable is from the time its definition is

encountered during the execution of the whole program, until the program is finished• If a function with locals is called several times, then those variables

are created and destroyed, created and destroyed, over and over for each call, their lifespan is intermittent

Page 18: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Passing Parameters by value

Page 19: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Can a function change a parameter permanently?• Given this little function• def fun1 (a):

a = 15• Does it change its parameter inside the function? Yes. After that

statement, a would be 15. How long would a be 15? Until it was changed again or until the function ended• Does it change the argument which was used to call the function, that

matched the parameter? No, it does not.

Page 20: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Passing by value

• In Python the default way that arguments are passed to become parameters in a function is by value.• That means that the function gets a copy of the argument’s value for

the parameter to use. Whatever happens to the parameter in the function has NO effect on the argument in the calling code.• Making permanent changes is what the return statement is for.• You use the return statement to send back values to the calling code.

Page 21: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Why?

• Why discuss this? This is described in the other examples of functions• Python and other languages have another way to pass arguments to

parameters which does allow for a permanent change• This way is called passing by reference• We will see this later when we get into lists. For now, just remember

that passing by value is the default way and it means that functions do NOT make permanent changes to their parameters.

Page 22: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Call Stacks, Arguments and Returns

And a bit about Recursion

Page 23: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Functions can call other functions!

• It is a natural tendency to break a big problem up into smaller problems• This can be repeated several times – funA can be broken up into funA1 and

funA2 and funA3, which can be broken into funA11 and funA12 and so on• The execution proceeds just as in other examples of function calls.

• The interpreter keeps track of all these function calls using a data structure called a “call stack”.

Page 24: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

More semantics - Call stacks (stack frames)• To keep track of all the activity involved in a function call, the

interpreter uses a data structure called a “call stack”• It is a stack of records, each record is about a function call.• When a function call is made, a record of that fact is put on top of the

call stack. That indicates that that function is the one executing.• When a function call is finished and is ready to return, its record is

removed from the top of the stack to say it is no longer the one running. The record underneath that is the one belonging to the function which called.

Page 25: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

More semantics – Arguments and Parameters• Parameters are named in the def statement (can only be identifiers)• They are placeholders, waiting to be filled in when the function runs• There can be any number of parameters (but don’t go overboard! more than 10

is excessive)• Arguments are named in the function call• Arguments have values which are copied to the parameters• Arguments can be identifiers, expressions, constants• The number of arguments must match the number of parameters• The names of arguments do NOT have to match the names of the parameters• The types of arguments and parameters should match or at least be similar

Page 26: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

The return statement

• The return statement tells Python that the execution of the current function (the function that the return statement is in) is done and that control passes back to the function which called it• The return statement can have nothing after the keyword, in which

case Python returns the special value None• Or the return statement can have one or more expressions after the

keyword (yes, a Python function can return multiple values!)• When the return statement is executed, the function is finished –

therefore, do NOT put code after a return statement, it will never execute!

Page 27: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Recursion

• Functions can call themselves! That is called Recursion. • See chapter 12 for details. • Recursion is a powerful technique but must be written carefully or it

will cause infinite loops.• Don’t worry about recursion until it is covered in class

Page 28: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Documenting a function

Page 29: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Documenting a function definition

• We have a template for information that we need you to put at the top of each function - if you do this as part of your design, you will be ready when you write the implementation• The name of the function• The purpose of the function• The preconditions = the parameters – their meaning, not just their

number!• The postconditions = the return value and/or output • The design

Page 30: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

Example:

‘’’ function draw_circle purpose: draws the circle specified on the graphics window, using the Zelle graphics library preconditions: x and y of center of circle, radius of circle, color of line to draw with, and graphwin object to display circle on postconditions: nothing returned, circle as specified drawn on given windowDesign1. Create circle object with point and radius provided2. Set the color of the circle to given color3. Draw the circle‘’’

Page 31: Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new

A docstring

• Some people and software companies have a standard requirement of putting all this information in a triply-quoted string at the very top of the function.• It’s called a “docstring” in that case• Some software that professionals use can actually pull out those

comments to produce documentation for their company• In this class it’s up to you whether you use the ‘’’ or the # to make

these comments• Of course, you put your implementation between the lines of design

comments, as usual, when writing the Python code