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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Scope and Lifespan of Identifiers. Every function has a scope What does that mean? That means that every identifier that is created in a function (that’s.
Chapter 7: User-Defined Functions II
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Chapter 6 Modular Programming and Functions. 6.1 INTRODUCTION Several programmers work together in teams on the same project. In addition, there is the.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
Copyright © 2003 Pearson Education, Inc. Slide 1.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Main task -write me a program
Introduction to Methods
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
CS0004: Introduction to Programming Subprocedures and Modular Design.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Python Functions.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Documenting a function. Documenting a function definition We have a template for information that we need you to put at the top of each function - if.
Controlling Program Flow with Decision Structures.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Review Expressions and operators Iteration – while-loop – for-loop.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Programming Logic and Design Seventh Edition
Introduction To Repetition The for loop
Methods Chapter 6.
Topic: Functions – Part 2
Programmazione I a.a. 2017/2018.
User-Defined Functions
Functions Taken from notes by Dr. Neil Moore
Call Stacks, Arguments and Returns
Chapter 3 Simple Functions
Chapter 4 void Functions
Passing Parameters by value
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Topics Introduction to Functions Defining and Calling a Function
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Top-Down Design with Functions
Presentation transcript:

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 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

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)

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!

A Black Box You 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 Box InputOutput

Syntax of functions – two parts A function has to have a definition And a function needs to be called (otherwise it is not executed)

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

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

Functions Part 2 (Semantics)

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

Semantics of a function call (invocation) 1.The function which is doing the calling is paused – put on hold 2.Copies of the argument values are put in the places where the parameters are in the function definition code 3.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 calling 6.The calling function picks up where it left off, using the return value

Scope and Lifespan of Identifiers

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

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?”

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!

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

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

Passing Parameters by value

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.

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.

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.

Call Stacks, Arguments and Returns And a bit about Recursion

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”.

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.

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

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!

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

Documenting a function

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

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 window Design 1.Create circle object with point and radius provided 2.Set the color of the circle to given color 3.Draw the circle ‘’’

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