CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 1.

Slides:



Advertisements
Similar presentations
1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
Advertisements

JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Structured programming
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Outline 4.1 Introduction 4.2 Program Components in Python 4.3 Functions 4.4Module.
 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11 – JavaScript/Jscript: Functions Outline 11.1Introduction 11.2Program Modules in JavaScript.
The University of Texas – Pan American
1 Lecture 3 Part 1 Functions with math and randomness.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
CSCI/CMPE 4341 Topic: Programming in Python Review: Final Exam Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
Review for Nested loops & Math class methods & User defined methods.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Introduction Modules Small pieces of a problem ▴ e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 4: Control Structures (Part 2) Xiang Lian The University of Texas – Pan American Edinburg, TX
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions – Exercises Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Functions Course conducted by: Md.Raihan ul Masood
Chapter 3 - Functions Outline 3.1 Introduction
Methods Chapter 6.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Chapter 10 - JavaScript: Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Chapter 3 - Functions Outline 3.1 Introduction
Presentation transcript:

CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX

Objectives In this chapter, you will: – Understand how to construct programs modularly from small pieces called functions – Create new functions – Learn how to exchange information between functions – Know how to generate random numbers – Explore the visibility of identifiers in programs – Use recursive functions – Become familiar with default and keyword arguments 2

Introduction The best way to maintain a large program is to break it down into smaller more manageable pieces – These pieces are called components Problem solving – Divide and conquer 3

Program Components in Python Components – Consist of functions, classes, modules and packages – In most cases programs are a combination of programmer defined functions and classes with predefined ones Programmer defined functions – Programs the perform specific tasks and execute at various points in the program Modules – Used to perform common tasks – Help to eliminate code rewriting – The standard library A collection of modules provided with the python language 4

Program Components in Python (cont'd) Functions – Invoked by a function call Specifies the function name and its arguments – Arguments Additional information the function needs to compete its task – The return task Information that the function returns to the source that invoked it for use elsewhere in the program 5

Example of Program Components in Python Fig. 4.1Hierarchical boss-function/worker-function relationship. boss worker1worker2worker3 worker4worker5 6

Functions – Allow a programmer to modularize a program – Variables created in a function are local to that function – Parameters Also local variables Provide a means for one function to communicate with another Purpose – Functions support the divide and conquer strategy – Help enhance software reusability – Acts as building blocks for the program – Avoids code repetition 7

Module math Functions Module – Contains function definitions and other elements All of which are related in some way – Calling a function functionName ( argument1, argument2 ) – The import keyword is used to include a module – Invoking functions from a module Use the module name followed by the dot operator (.) moduleName.functionName( argument ) 8

Examples of Module math Functions import math print (math.sqrt(900)) c=13 d=3 f=4 print(math.sqrt(c+d*f)) 9

More math Functions 10

More math Functions (cont'd) 11

Examples of Floor and Ceiling floor function: – math.floor(2.10) = 2 – math.floor(2.00) = 2 – math.floor(1.90) = 1 – math.floor(1.80) = 1 ceil function: – math.ceil(0.00) = 0 – math.ceil(0.10) = 1 – math.ceil(0.20) = 1 – math.ceil(0.30) = 1 12

User-Defined Functions Definitions – Functions must be defined before they are used – def functionName ( paramList ): functionName is a valid identifier paramList is a comma separated list of parameters received The actions of the functions then follows – They should all be indented appropriately – The actions are also called the block or the function body 13

 2002 Prentice Hall. All rights reserved. Outline Fig04_04.py Program Output # Fig. 4.4: fig04_04.py # Creating and using a programmer-defined function. # function definition def square( y ): return y * y for x in range( 1, 11 ): print (square( x )) print() This is a function definition, the function is called square and is passed the value y The function returns the passed value multiplied by itself This calls the square function and passes it the value x 14

 2002 Prentice Hall. All rights reserved. Outline Fig04_05.py # Fig. 4.5: fig04_05.py # Finding the maximum of three integers. def maximumValue( x, y, z ): maximum = x if y > maximum: maximum = y if z > maximum: maximum = z return maximum a = int( input( "Enter first integer: " ) ) b = int( input( "Enter second integer: " ) ) c = int( input( "Enter third integer: " ) ) # function call print ("Maximum integer is:", maximumValue( a, b, c ) ) print () # print new line d = float( input( "Enter first float: " ) ) e = float( input( "Enter second float: " ) ) f = float( input( "Enter third float: " ) ) print ("Maximum float is: ", maximumValue( d, e, f )) print () g = input( "Enter first string: " ) h = input( "Enter second string: " ) i = input( "Enter third string: " ) print ("Maximum string is: ", maximumValue( g, h, i )) This is a function that receives tree values The function determines the greater of three numbers and returns it Gets three integers, passes them to the maximumValue function, and displays the results to the user The same process is performed on float and string variables to show the diversity of the function 15

Random-Number Generation The random module – Used to generate a random number for the programmer – Function randrange Generates a number from the first argument up to, but not including, the second argument Each number in the range has the same likelihood of being selected by the function 16

 2002 Prentice Hall. All rights reserved. Outline Fig04_06.py Program Output # Fig. 4.6: fig04_06.py # Random integers produced by randrange. import random for i in range( 1, 21 ): # simulates 20 die rolls print ("%10d" % (random.randrange( 1, 7 )), end ="") if i % 5 == 0: # print newline every 5 rolls print () The randrange function is called passing the values 1 and 7 As shown by the output the number range is really from 1 to 6 not 7 The random module is imported 17

 2002 Prentice Hall. All rights reserved. Outline Fig04_07.py # Fig. 4.7: fig04_07.py # Roll a six-sided die 6000 times. import random frequency1 = 0 frequency2 = 0 frequency3 = 0 frequency4 = 0 frequency5 = 0 frequency6 = 0 for roll in range( 1, 6001 ): # 6000 die rolls face = random.randrange( 1, 7 ) if face == 1: # frequency counted frequency1 += 1 elif face == 2: frequency2 += 1 elif face == 3: frequency3 += 1 elif face == 4: frequency4 += 1 elif face == 5: frequency5 += 1 elif face == 6: frequency6 += 1 else: # simple error handling print ("should never get here!") print (frequency1) print (frequency2) print (frequency3) print (frequency4) print (frequency5) print (frequency6) This nested if is used to keep track of the occurrence of each number generated Creates a loop that executes 6000 times Again the randrange function is called with values 1 and 7 passed to it This else statement should never be used by the program but is there for good programming purposes 18

 2002 Prentice Hall. All rights reserved. Outline Fig04_08.py # Fig. 4.8: fig04_08.py # Craps. import random def rollDice(): die1 = random.randrange( 1, 7 ) die2 = random.randrange( 1, 7 ) workSum = die1 + die2 print ("Player rolled %d + %d = %d" % ( die1, die2, workSum )) return workSum sum = rollDice() # first dice roll if sum == 7 or sum == 11: # win on first roll gameStatus = "WON" elif sum == 2 or sum == 3 or sum == 12: # lose on first roll gameStatus = "LOST" else: # remember point gameStatus = "CONTINUE" myPoint = sum print ("Point is", myPoint) while gameStatus == "CONTINUE": # keep rolling sum = rollDice() if sum == myPoint: # win by making point gameStatus = "WON" elif sum == 7: # lose by rolling 7: gameStatus = "LOST" if gameStatus == "WON": print ("Player wins") else: print ("Player loses") The start of the rollDice function Prints out the value of each random number along with their sum, which is also returned An if statement that determines the next step in the game based on what the player rolled The while statement will loop until the player has wither lost or won the game 19

Scope Rules Namespaces store information about an identifier and a value to which it is bound Local namespace – Contains values that were created in a block – Each function has a unique local namespace Global namespace – Stores the names of date, functions and classes defined within the file or module – Each module contain a __name__ It holds the name of the module Function dir() to show variables under the current namespace – The global keyword Used to automatically search the global namespace 20

Scope Rules (cont'd) Built-in namespace – Not usually modified by programmers – Contains functions such as input, int, and range – The built-in namespace is included when the interpreter starts 21

 2002 Prentice Hall. All rights reserved. Outline Fig04_10.py # Fig. 4.10: fig04_10.py # Scoping example. x = 1 # global variable # alters the local variable x, shadows the global variable def a(): x = 25 print ("\nlocal x in a is", x, "after entering a") x += 1 print ("local x in a is", x, "before exiting a") # alters the global variable x def b(): global x print ("\nglobal x is", x, "on entering b") x *= 10 print ("global x is", x, "on exiting b") print ("global x is", x) x = 7 print ("global x is", x) a() b() a() b() print ("\nglobal x is", x) This is a global variable and can be used by any function in the program Changes the value of x to 7Has its own value of x therefore the global value is hidden Function b uses and modifies the value of the global x 22

Keyword import and Namespaces Importing – Affects a programs namespace Use the keyword import followed by the desired module – import math dir() dir(math) – import random dir(random) – dir(__builtins__) 23

Recursion Method that calls itself A recursive method solves only a simple problem (base case) For any thing other than the base case, it calls itself with a slightly simpler problem – Eventually it becomes the base case for which it knows the answer 24

Example of Factorial # n! def Factorial (number): # base case if number <= 1: return 1 else: return number * Factorial(number -1) print (Factorial (4)) 25

Example Using Recursion: The Fibonacci Series The Fibonacci series – Each number is composed of the sum of the two previous numbers Fibonacci( n ) = Fibonacci( n – 1 ) + Fibonacci( n – 2 ) Fibonacci( 1 ) = 1 and Fibonacci( 0 ) = 0 – 0, 1, 1, 2, 3, 5, 8, 13, … 26

 2002 Prentice Hall. All rights reserved. Outline Fig04_18.py Program Output # Fig. 4.18: fig04_18.py # Recursive fibonacci function. def fibonacci( n ): if n < 0: print ("Cannot find the fibonacci of a negative number.") if n == 0 or n == 1: # base case return n else: # two recursive calls return fibonacci( n - 1 ) + fibonacci( n - 2 ) number = int(input( "Enter an integer: " ) ) result = fibonacci( number ) print ("Fibonacci(%d) = %d" % ( number, result )) Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1 Enter an integer: 2 Fibonacci(2) = 1 If n is either 0 or 1 then return that value If the value is neither zero or one then two recursive calls are made 27

Default Arguments Function arguments – Functions may commonly receive a particular value type – When this is true a default argument can be set Must appear to the right of any other arguments – A default value can also be set If passes a value then the default value is overridden 28

 2002 Prentice Hall. All rights reserved. Outline Fig04_20.py Program Output # Fig. 4.20: fig04_20.py # Using default arguments. # function definition with default arguments def boxVolume( length = 1, width = 1, height = 1 ): return length * width * height print ("The default box volume is:", boxVolume() ) print ("\nThe volume of a box with length 10," ) print ("width 1 and height 1 is:", boxVolume( 10 ) ) print ("\nThe volume of a box with length 10," ) print ("width 5 and height 1 is:", boxVolume( 10, 5 ) ) print ("\nThe volume of a box with length 10," ) print ("width 5 and height 2 is:", boxVolume( 10, 5, 2 ) ) The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 Sets the three values, defaulted to 1 When this is called the default values will be used The 10 will replace the left most 1 and the other default values will be used Here two values are sent meaning only height will use its default value In this case no default values were used 29

Keyword Arguments Keyword arguments – Just as a programmer specifies default arguments keyword arguments can be specified as well – Allows parameter to be passed in any order so long as they are explicitly stated – Will set the values that were not passed to the default 30

 2002 Prentice Hall. All rights reserved. Outline Fig04_21.py Program Output # Fig. 4.21: fig04_21.py # Keyword arguments example. def generateWebsite( name, url = " Flash = "no", CGI = "yes" ): print ("Generating site requested by", name, "using url", url) if Flash == "yes": print ("Flash is enabled" ) if CGI == "yes": print ("CGI scripts are enabled" ) print () # prints a new line generateWebsite( "Deitel" ) generateWebsite( "Deitel", Flash = "yes", url = " ) generateWebsite( CGI = "no", name = "Prentice Hall" ) Generating site requested by Deitel using url CGI scripts are enabled Generating site requested by Deitel using url Flash is enabled CGI scripts are enabled Generating site requested by Prentice Hall using url The definition of this function specifies keywords, some of which have default values as well Sets Deitel as the first value and uses the defaults for all the others In order the variables are given new values and CGI uses the default The values need not be entered in order 31

32