The Quick Python Book, Fourth Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

9 Functions

 

This chapter covers

  • Defining functions
  • Using function parameters
  • Passing mutable objects as parameters
  • Understanding local and global variables
  • Creating and using generator functions
  • Creating and using lambda expressions
  • Using decorators

This chapter assumes that you’re familiar with function definitions in at least one other computer language and with the concepts that correspond to function definitions, arguments, parameters, and so forth.

9.1 Basic function definitions

The basic syntax for a Python function definition is

def name(parameter1, parameter2, . . .):
   body

As it does with control structures, Python uses indentation to delimit the body of the function definition. The following simple example puts the code to calculate a factorial into a function body, so you can call a fact function to obtain the factorial of a number:

def fact(n):
    '''Return the factorial of the given number.''' #1
    r = 1
    while n > 0:
        r = r * n
        n = n - 1
    return r                                        #2

If the function has a return statement, like the preceding one, that value will be returned to the code calling the function and can be assigned to a variable. If no return is used, the function will return a None value.

9.2 Function parameter options

9.2.1 Positional parameters

9.2.2 Passing arguments by parameter name

9.2.3 Variable numbers of arguments

9.2.4 Mixing argument-passing techniques

9.3 Mutable objects as arguments

9.3.1 Mutable objects as default values

9.4 Local, nonlocal, and global variables

9.5 Assigning functions to variables

9.6 lambda expressions

9.7 Generator functions

9.8 Decorators

9.9 Useful functions