Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington."— Presentation transcript:

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

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

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

4 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(23.4567, 2) When the round function returns its result, the return value is stored in the variable ‘ answer ’.

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

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

7 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(23.4567, 2) When the round function returns its result, the return value is stored in the variable ‘ answer ’. statement)

8 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

9 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

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

11 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

12 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

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

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

15 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

16 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

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

18 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

19 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

20 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

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

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

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

24 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

25 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()

26 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

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

28 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

29 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

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

31 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()

32 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

33 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()

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

35 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

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

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

38 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. # @param sideLength the length of a side of cube # @return the volume of the cube # def cubeVolume(sideLength) : volume = sideLength ** 3 return volume ## Computes the volume of a cube. # @param sideLength the length of a side of cube # @return 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.

39 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

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

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

42 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

43 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

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

45 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 = 10000 # A global variable def withdraw(amount) : # This function intends to access the # global ‘balance’ variable global balance if balance >= amount : balance = balance - amount balance = 10000 # A global variable def withdraw(amount) : # This function intends to access the # global ‘balance’ variable global balance if balance >= amount : balance = balance - amount


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

Similar presentations


Ads by Google