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

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

Embed Size (px)

Citation preview

  • CSCI/CMPE 4341 Topic: Programming in PythonChapter 5: FunctionsXiang LianThe University of Texas Pan AmericanEdinburg, TX [email protected] *

  • ObjectivesIn this chapter, you will:Understand how to construct programs modularly from small pieces called functionsCreate new functionsLearn how to exchange information between functionsKnow how to generate random numbersExplore the visibility of identifiers in programsUse recursive functionsBecome familiar with default and keyword arguments *

  • IntroductionThe best way to maintain a large program is to break it down into smaller more manageable piecesThese pieces are called componentsProblem solvingDivide and conquer

    *

  • Program Components in PythonComponentsConsist of functions, classes, modules and packagesIn most cases programs are a combination of programmer defined functions and classes with predefined onesProgrammer defined functionsPrograms the perform specific tasks and execute at various points in the programModulesUsed to perform common tasksHelp to eliminate code rewritingThe standard libraryA collection of modules provided with the python language*

  • Program Components in Python (cont'd)FunctionsInvoked by a function callSpecifies the function name and its argumentsArgumentsAdditional information the function needs to compete its taskThe return taskInformation that the function returns to the source that invoked it for use elsewhere in the program*

  • Example of Program Components in PythonFig. 4.1Hierarchical boss-function/worker-function relationship. *

  • FunctionsFunctionsAllow a programmer to modularize a programVariables created in a function are local to that functionParametersAlso local variablesProvide a means for one function to communicate with anotherPurposeFunctions support the divide and conquer strategyHelp enhance software reusabilityActs as building blocks for the programAvoids code repetition*

  • Module math FunctionsModuleContains function definitions and other elementsAll of which are related in some wayCalling a functionfunctionName ( argument1, argument2 )The import keyword is used to include a moduleInvoking functions from a moduleUse the module name followed by the dot operator (.)moduleName.functionName( argument )

    *

  • Examples of Module math Functionsimport mathprint (math.sqrt(900))

    c=13d=3f=4print(math.sqrt(c+d*f))*

  • More math Functions*

    Method

    Description

    Example

    acos( x )

    Trigonometric arc cosine of x (result in radians)

    acos( 1.0 ) is 0.0

    asin( x )

    Trigonometric arc sine of x (result in radians)

    asin( 0.0 ) is 0.0

    atan( x )

    Trigonometric arc tangent of x (result in radians)

    atan( 0.0 ) is 0.0

    ceil( x )

    Rounds x to the smallest integer not less than x

    ceil( 9.2 ) is 10.0

    ceil( -9.8 ) is -9.0

    cos( x )

    Trigonometric cosine of x (x in radians)

    cos( 0.0 ) is 1.0

    exp( x )

    Exponential function ex

    exp( 1.0 ) is 2.71828

    exp( 2.0 ) is 7.38906

    fabs( x )

    Absolute value of x

    fabs( 5.1 ) is 5.1

    fabs( -5.1 ) is 5.1

    floor( x )

    Rounds x to the largest integer not greater than x

    floor( 9.2 ) is 9.0

    floor( -9.8 ) is -10.0

    fmod( x, y )

    Remainder of x/y as a floating point number

    fmod( 9.8, 4.0 ) is 1.8

  • More math Functions (cont'd)*

    hypot( x, y )

    hypotenuse of a triangle with sides of length x and y: sqrt( x2 + y2 )

    hypot( 3.0, 4.0 ) is 5.0

    log( x )

    Natural logarithm of x (base e)

    log( 2.718282 ) is 1.0

    log( 7.389056 ) is 2.0

    log10( x )

    Logarithm of x (base 10)

    log10( 10.0 ) is 1.0

    log10( 100.0 ) is 2.0

    pow( x, y )

    x raised to power y (xy)

    pow( 2.0, 7.0 ) is 128.0

    pow( 9.0, .5 ) is 3.0

    sin( x )

    trigonometric sine of x

    (x in radians)

    sin( 0.0 ) is 0.0

    sqrt( x )

    square root of x

    sqrt( 900.0 ) is 30.0

    sqrt( 9.0 ) is 3.0

    tan( x )

    trigonometric tangent of x (x in radians)

    tan( 0.0 ) is 0.0

    Fig. 4.3math module functions.

  • Examples of Floor and Ceilingfloor 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 *

  • User-Defined FunctionsDefinitionsFunctions must be defined before they are useddef functionName ( paramList ):functionName is a valid identifierparamList is a comma separated list of parameters receivedThe actions of the functions then followsThey should all be indented appropriatelyThe actions are also called the block or the function body

    *

    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 definitiondef square( y ):return y * y for x in range( 1, 11 ):print (square( x )) print()

    14 9 16 25 36 49 64 81 100

    *

    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 callprint ("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 ))

    *

  • Random-Number GenerationThe random moduleUsed to generate a random number for the programmerFunction randrangeGenerates a number from the first argument up to, but not including, the second argumentEach number in the range has the same likelihood of being selected by the function*

    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 rollsprint ("%10d" % (random.randrange( 1, 7 )), end ="")

    if i % 5 == 0: # print newline every 5 rollsprint () 5 3 3 3 2 3 2 3 3 4 2 3 6 5 4 6 2 4 1 2 *

    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 = 0frequency2 = 0frequency3 = 0frequency4 = 0frequency5 = 0frequency6 = 0 for roll in range( 1, 6001 ): # 6000 die rollsface = random.randrange( 1, 7 )

    if face == 1: # frequency countedfrequency1 += 1elif face == 2:frequency2 += 1elif face == 3:frequency3 += 1elif face == 4:frequency4 += 1elif face == 5:frequency5 += 1elif face == 6:frequency6 += 1else: # simple error handlingprint ("should never get here!")print (frequency1)print (frequency2)print (frequency3)print (frequency4)print (frequency5)print (frequency6)

    *

    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 + die2print ("Player rolled %d + %d = %d" % ( die1, die2, workSum ))

    return workSum

    sum = rollDice() # first dice roll

    if sum == 7 or sum == 11: # win on first rollgameStatus = "WON"elif sum == 2 or sum == 3 or sum == 12: # lose on first rollgameStatus = "LOST"else: # remember pointgameStatus = "CONTINUE"myPoint = sumprint ("Point is", myPoint) while gameStatus == "CONTINUE": # keep rollingsum = rollDice()

    if sum == myPoint: # win by making pointgameStatus = "WON"elif sum == 7: # lose by rolling 7:gameStatus = "LOST"if gameStatus == "WON":print ("Player wins")else:print ("Player loses")

    *

  • Scope RulesNamespaces store information about an identifier and a value to which it is boundLocal namespaceContains values that were created in a blockEach function has a unique local namespaceGlobal namespaceStores the names of date, functions and classes defined within the file or moduleEach module contain a __name__It holds the name of the moduleFunction dir() to show variables under the current namespaceThe global keywordUsed to automatically search the global namespace

    *

  • Scope Rules (cont'd)Built-in namespaceNot usually modified by programmersContains functions such as input, int, and rangeThe built-in namespace is included when the interpreter starts

    *

    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 variabledef a(): x = 25

    print ("\nlocal x in a is", x, "after entering a")x += 1print ("local x in a is", x, "before exiting a")

    # alters the global variable xdef b():global x

    print ("\nglobal x is", x, "on entering b")x *= 10print ("global x is", x, "on exiting b")

    print ("global x is", x)

    x = 7print ("global x is", x)

    a()b()a()b()

    print ("\nglobal x is", x)

    *

  • Keyword import and NamespacesImportingAffects a programs namespaceUse the keyword import followed by the desired moduleimport mathdir()dir(math)import randomdir(random)dir(__builtins__)

    *

  • RecursionMethod that calls itselfA recursive method solves only a simple problem (base case)For any thing other than the base case, it calls itself with a slightly simpler problemEventually it becomes the base case for which it knows the answer*

  • Example of Factorial# n!def Factorial (number):# base caseif number
  • Example Using Recursion: The Fibonacci SeriesThe Fibonacci seriesEach number is composed of the sum of the two previous numbersFibonacci( n ) = Fibonacci( n 1 ) + Fibonacci( n 2 )Fibonacci( 1 ) = 1 and Fibonacci( 0 ) = 00, 1, 1, 2, 3, 5, 8, 13, *

    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 casereturn nelse:

    # two recursive callsreturn fibonacci( n - 1 ) + fibonacci( n - 2 )

    number = int(input( "Enter an integer: " ) )result = fibonacci( number )print ("Fibonacci(%d) = %d" % ( number, result ))

    Enter an integer: 0Fibonacci(0) = 0 Enter an integer: 1Fibonacci(1) = 1Enter an integer: 2Fibonacci(2) = 1 *

  • Default ArgumentsFunction argumentsFunctions may commonly receive a particular value typeWhen this is true a default argument can be setMust appear to the right of any other argumentsA default value can also be setIf passes a value then the default value is overridden*

    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 argumentsdef 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: 1The volume of a box with length 10,width 1 and height 1 is: 10The volume of a box with length 10,width 5 and height 1 is: 50The volume of a box with length 10,width 5 and height 2 is: 100

    *

  • Keyword ArgumentsKeyword argumentsJust as a programmer specifies default arguments keyword arguments can be specified as wellAllows parameter to be passed in any order so long as they are explicitly statedWill set the values that were not passed to the default

    *

    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 = "www.deitel.com",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 = "www.deitel.com/new" ) generateWebsite( CGI = "no", name = "Prentice Hall" )Generating site requested by Deitel using url www.deitel.com CGI scripts are enabled Generating site requested by Deitel using url www.deitel.com/new Flash is enabled CGI scripts are enabledGenerating site requested by Prentice Hall using url www.deitel.com*

  • *

    Some slides are borrowed and revised from lecture slides of the textbook**