CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Introduction to C Programming
Overview creating your own functions calling your own functions.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Introduction to C Programming
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Python quick start guide
Writing Classes (Chapter 4)
Slides by Donald W. Smith
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Procedural programming in Java Methods, parameters and return values.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
COM S 207 Method Instructor: Ying Cai Department of Computer Science Iowa State University
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
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.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
C# Programming Methods.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
4 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
PYTHON FUNCTIONS. What you should already know Example: f(x) = 2 * x f(3) = 6 f(3)  using f() 3 is the x input parameter 6 is the output of f(3)
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
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.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 9: Value-Returning Functions
Introduction to Programming
Introduction to Programming
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
COMP 170 – Introduction to Object Oriented Programming
Department of Computer Science,
Suppose we want to print out the word MISSISSIPPI in big letters.
Functions CIS 40 – Introduction to Programming in Python
Functions.
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Coding Concepts (Basics)
Introduction to Programming
Introduction to Programming
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Introduction to Programming
Introduction to Programming
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Presentation transcript:

CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington

What is a Function Series of programming statements with a name We have used: –print function: print(“Hi there”) –round function: answer = round ( , 2) Names are “print” and “round” To use a function we “call” the function –We ask the function round to take the number and round it to two decimal places Flow of control leaves our program executes “round” and returns to our program

What is a Function Series of programming statements with a name We have used: –print function: print(“Hi there”) –round function: answer = round ( , 2) Names are “print” and “round” Functions have a format answer = round ( , 2) Name of function actual parameters Returned value

Function Return Values (1) The “output” that the round function computes is called the return value. Functions return only one value. The return value of a function is returned to the point in your program where the function was called. answer = round( , 2) When the round function returns its result, the return value is stored in the variable ‘ answer ’.

Calling Functions (1) You call a function in order to execute its instructions. answer = round( , 2) # Sets answer to –By using the expression round( , 2), your program calls the round function, asking it to round to two decimal digits.

Function Arguments (2) Functions can receive multiple arguments or it is also possible to have functions with no arguments print().

Function Return Values (1) The “output” that the round function computes is called the return value. Functions return only one value. The return value of a function is returned to the point in your program where the function was called. answer = round( , 2) When the round function returns its result, the return value is stored in the variable ‘ answer ’. statement)

What is a Function, continued The beauty is: –You do not need to know how the function works exactly –You DO need to know Guzintas Guzoutas Black Box – –A good function is a black box

Creating our own functions Up to now we have used functions created by others Now we create our own We need to learn - How to define the header –So others will know how to call us We need to learn – How to accept parameters –So we can use data the world sends us We need to learn – How to return a value –So the world knows what to expect back

To define a function format : A header and a body def ( ) :

Example: def addit(parm1, parm2): # header ans=parm1 + parm2 # body return ans # return Here the user gives the function two numbers or two variable The function addit adds them together and returns the sum to the user

Example: def addit(parm1, parm2): # header ans=parm1 + parm2 # body return ans # return Here the user gives the function two numbers or two variable The function addit adds them together and returns the sum to the user Name of Function parameter list

Testing a Function If you run a program containing just the function definition, then nothing happens. –After all, nobody is calling the function. In order to test the function, your program should contain –The definition of the function. –Statements that call the function and print the result.

Testing a function function must be defined before you use it To use it: # define the function def addit(parm1, parm2): ans=parm1 + parm2 return ans # use the function by calling it mysum = addit (5,2) print ("result of function call is = ", mysum)

Testing a function function must be defined before you use it To use it: def addit(parm1, parm2): ans=parm1 + parm2 return ans mysum = addit (5,2) print ("result of function call is = ", mysum) actual parameters formal parameters

Quick Check Define a function called raiseIt. This function will take two formal parameters. The first parameter will be the number that you want to raise to a certain power and the second number will be what power you want to raise the number to: so 2,3 would raise a 2 to the 3 rd power yielding an answer of 8. hint: remember the operator ** So, example 5 raised to the 4 th power would be 5 ** 4

The main Function When defining and using functions in Python, –Place all statements into functions even the code that calls a function you created –Specify one function as the starting point. main –Any legal name can be used for the starting point, but we chose ‘main’ since it is the required function name used by other common languages. Need one statement in the program that calls the main function.

What is main() We can have our usual programs as functions The name of our main program is main() –We define our program as a function as follows: def main(): print("Hi there") Nothing will run until we call this “function” we call it as follows main() main() #Now it will execute the “function” called main

Together def addit (parm1, parm2): answer = parm1 +parm2 return answer # def main(): print("Hi There") mysum=addit(4,5) print ("mysum=",mysum) # main() This statement is outside any function

Parameters There is a “hand-shake” that takes place between the definition of a function and the calling of the function. Calling function “main” sends Actual params 4 and 5 Called function addit definition has Formal params parm1 & parm2 4 and 5

What happens – addit is called def main(): mysum= addit (5, 4) print(mysum) main() def addit (parm1, parm2): sum = parm1 + parm2 return sum

What happens – addit is called def main(): mysum= addit (5, 4) print(mysum) main() def addit (parm1, parm2): sum = parm1 + parm2 return sum

What happens – addit is called def main(): mysum= addit (5, 4) print(mysum) main() def addit (parm1, parm2): sum = parm1 + parm2 return sum

Why does addit work with any values It works with any values because it uses parameters that are passed into parm1 and paarm2 –parm1 and parm2 Any values get copied and addit can be used over and over

def addit (var1, var2): answer = var1 +var2 return answer # def main(): mysum=addit(4,5) print ("mysum=",mysum) ans=addit(105, 3) print ("ans=", ans) numb1 = 25 numb2 = 14 newAns = addit (numb1, numb2) print("newAns = ", newAns) # main()

Formal and Actual Parameters When defining a function we use Formal Parameters –A place holder that will get information that is passed to the method (copied in) –Formal parameters are used inside the function to do calculations and testing, they are empty baskets that will be filled in when the function is called When calling a function we use Actual Parameters –The real data that we want the function to operate on

Parameter Passing Steps result1 = cubeVolume(2) def cubeVolume(sideLength): volume = sideLength * 3 return volume def cubeVolume(sideLength): volume = sideLength * 3 return volume

Return Values Functions can return a value or they do not have to Returned value goes back to user of the function and is specified when the function is called mysum receives result of the addit function mysum=addit(4,5) Example of a returned value def addit (parm1, parm2): answer = parm1 + parm2 return answer

Return Values Functions can return a value or they do not have to Returned value goes back to user of the function and is specified when the function is called mysum receives result of the addit function mysum=addit(4,5) Example of a returned value def addit (parm1, parm2): answer = parm1 + parm2 return answer

Return statement Exits the function Returns the value to the calling program

One Return value – Yet ….. def testIt(val1, val2): if val1>val2: return True else: return False def main(): answer = testIt(7,5) print(answer) main()

Multiple return Statements (1) A function can use multiple return statements –But every branch must have a return statement def cubeVolume(sideLength): if (sideLength < 0): return 0 return sideLength * 3 def cubeVolume(sideLength): if (sideLength < 0): return 0 return sideLength * 3

Example without return Create a function to print a letter using a name provided – save as PRTname.py def letter (name): print("Dear " +name + ", \n How are you today") # def main(): letter(“Dr. Tom Way") # main()

Making function available We create a function we love We want to use it over and over in all our programs How can we do it? Python functions like round is easy: –Available through the Python standard library –What about functions we write?

The import makes it possible The function we want to re-use –Must be in the same folder as our new program –We must know the name of the program in which it was defined –We must know the name of the function –We must know how to call the function What are the parameters it needs and what types (int, float, string ) Will it give us back a value

Experiment Type in the following code and save as XXPGM.py # XXPGM.py # def addit(parm1, parm2): # header ans=parm1 + parm2 # body return ans # return # def main(): myans = addit(5,2) print(myans)

Use in New program: myPGM.py Type in the following and save to myPGM.py Put myPGM.py in same folder as XXPGM.py #myPGM.py from XXPGM import addit print("I am in myPGM ") num1 = 4 num2 =6 newANS=addit (num1,num2) print ("newANS = ", newANS)

Function Comments Whenever you write a function, you should comment its behavior. Comments are for human readers, not compilers. ## Computes the volume of a cube. sideLength the length of a side of cube the volume of the cube # def cubeVolume(sideLength) : volume = sideLength ** 3 return volume ## Computes the volume of a cube. sideLength the length of a side of cube the volume of the cube # def cubeVolume(sideLength) : volume = sideLength ** 3 return volume Function comments explain the purpose of the function, the meaning of the parameter variables and the return value, as well as any special requirements.

Implementing a function: Steps 1)Describe what the function should do. 2)Determine the function’s “inputs”. 3)Determine the types of parameter values and the return value. 4)Write pseudocode for obtaining the desired result. 5)Implement the function body. 6)Test your function. –Design test cases and code def pyramidVolume(height, baseLength) : baseArea = baseLength * baseLength return height * baseArea / 3 def pyramidVolume(height, baseLength) : baseArea = baseLength * baseLength return height * baseArea / 3

Variable Scope Scop of a variable –Part of the program which can access this variable Variables can be declared: –Inside a function Known as ‘local variables’ Only available inside this function Parameter variables are like local variables –Outside of a function Sometimes called ‘global scope’ Can be used (and changed) by code in any function How do you choose? The scope of a variable is the part of the program in which it is visible.

–sum, square & i are local variables in main def main() : sum = 0 for i in range(11) : square = i * i sum = sum + square print(square, sum) def main() : sum = 0 for i in range(11) : square = i * i sum = sum + square print(square, sum) Examples of Scope The scope of a variable is the part of the program in which it is visible. sum i square

Local Variables of functions Variables declared inside one function are not visible to other functions –sideLength is local to main –Using it outside main will cause a compiler error def main(): sideLength = 10 result = cubeVolume() print(result) def cubeVolume(): return sideLength * sideLength * sideLength # ERROR def main(): sideLength = 10 result = cubeVolume() print(result) def cubeVolume(): return sideLength * sideLength * sideLength # ERROR

Re-using Names for Local Variables Variables declared inside one function are not visible to other functions –result is local to square and result is local to main –They are two different variables and do not overlap def square(n): result = n * n return result def main(): result = square(3) + square(4) print(result) def square(n): result = n * n return result def main(): result = square(3) + square(4) print(result) result

Global Variables They are variables that are defined outside functions. A global variable is visible to all functions that are defined after it. However, any function that wishes to use a global variable must include a global declaration.

Example Use of a Global Variable If you omit the global declaration, then the balance variable inside the withdraw function is considered a local variable. balance = # A global variable def withdraw(amount) : # This function intends to access the # global ‘balance’ variable global balance if balance >= amount : balance = balance - amount balance = # A global variable def withdraw(amount) : # This function intends to access the # global ‘balance’ variable global balance if balance >= amount : balance = balance - amount