Python Functions

A function is a block of organized, reusable code that is used to perform a single, or related action.

Functions help improve the modularity of applications and code reuse. You already know that Python provides many built-in functions, such as print(). You can also create your own functions, which are called user-defined functions.


Defining a Function

You can define a function with the functionality you want. Here are the simple rules:

  • Function code blocks begin withdefthe keyword, followed by the function identifier name and parentheses.()。
  • Any incoming parameters and arguments must be placed within the parentheses. The parentheses can be used to define parameters.
  • The first statement of a function can optionally be a docstring — used to store a function description.
  • The function body starts with a colon and is indented.
  • return [expression]Ends the function, optionally returning a value to the caller. A return with no expression is equivalent to returning None.

Syntax

def functionname( parameters ): "function_docstring" function_suite return [expression]

By default, parameter values and parameter names are matched in the order defined in the function declaration.

Example

The following is a simple Python function that takes a string as an incoming parameter and prints it to the standard display device.

Example (Python 2.0+)

def printme( str ): "Print the passed string to the standard display device." print str return

Calling a Function

Defining a function only gives the function a name, specifies the parameters it contains, and the structure of the code block.

Once the basic structure of this function is complete, you can call and execute it from another function, or directly from the Python prompt.

The following example calls the printme() function:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Define function def printme( str ): "Print any string passed in" print str return # Call the function printme("I am calling a user-defined function!") printme("Calling the same function again")

The output of the above example is:

I want to call a user-defined function!
Call the same function again

Parameter Passing

In Python, types belong to objects, and variables are untyped:

a=[1,2,3] a="Example"

In the above code,[1,2,3]is a List type,"Example"is a String type, while variable a has no type. It is merely a reference (a pointer) to an object. It can be a List type object, or it can point to a String type object.

Mutable and Immutable Objects

In Python, strings, tuples, and numbers are immutable objects, while list, dict, etc. are mutable objects.

  • Immutable types:Variable assignmenta=5and then assign againa=10Here, a new int value object 10 is actually generated, and then a is made to point to it, while 5 is discarded. It is not changing the value of a; it is equivalent to creating a new a.

  • Mutable types:Variable assignmentla=[1,2,3,4]and then assign againla[2]=5This changes the value of the third element of list la. la itself is not moved; only some of its internal values are modified.

Parameter passing in Python functions:

  • Immutable types:Similar to C++ pass-by-value, such as integers, strings, tuples. For example, fun(a) passes only the value of a, without affecting the object a itself. For instance, modifying the value of a inside fun(a) only modifies another copied object, not a itself.

  • Mutable types:Similar to C++ pass-by-reference, such as lists and dictionaries. For example, fun(la) actually passes la itself; after modification, la outside fun is also affected.

In Python, everything is an object. Strictly speaking, we cannot say pass-by-value or pass-by-reference; we should say passing immutable objects and passing mutable objects.

Python passing immutable object example

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- def ChangeInt( a ): a = 10 b = 2 ChangeInt(b) print b # The result is 2

In the example, there is an int object 2, and the variable pointing to it is b. When passed to the ChangeInt function, the variable b is copied in a pass-by-value manner, so both a and b point to the same int object. When a=10, a new int value object 10 is generated, and a is made to point to it.

Passing mutable object example

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def changeme( mylist ): "Modify the passed list" mylist.append([1,2,3,4]) print "Value inside the function:", mylist return # Call the changeme function mylist = [10,20,30] changeme( mylist ) print "Value outside the function:", mylist

In the example, the object passed into the function and the object to which new content is added at the end use the same reference, so the output is as follows:

函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
函数外取值:  [10, 20, 30, [1, 2, 3, 4]]

Parameters

The following are the formal parameter types that can be used when calling a function:

  • Required Parameters
  • Keyword Arguments
  • Default Arguments
  • Variable-length Parameters

Required Parameters

Required parameters must be passed to the function in the correct order. The number of arguments at the time of the call must be the same as the number at the time of declaration.

To call the printme() function, you must pass one parameter; otherwise, a syntax error will occur:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def printme( str ): "Print any string passed in" print str return # Call the printme function printme()

The output of the above example is:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme()
TypeError: printme() takes exactly 1 argument (0 given)

Keyword Arguments

Keyword arguments are closely related to function calls. Function calls use keyword arguments to determine the parameter values passed in.

Using keyword arguments allows the order of parameters in a function call to be inconsistent with the order in the declaration, because the Python interpreter can match parameter values using parameter names.

The following example uses parameter names when calling the function printme():

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def printme( str ): "Print any string passed in" print str return # Call the printme function printme( str = "My string")

The output of the above example is:

My string

The following example demonstrates more clearly that the order of keyword arguments does not matter:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def printinfo( name, age ): "Print any string passed in" print "Name: ", name print "Age ", age return # Call the printinfo function printinfo( age=50, name="miki" )

The output of the above example is:

Name:  miki
Age  50

Default Arguments

When calling a function, if the value of a default parameter is not passed, it is considered to be the default value. The following example will print the default age if age is not passed in:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def printinfo( name, age = 35 ): "Print any string passed in" print "Name: ", name print "Age ", age return # Call the printinfo function printinfo( age=50, name="miki" ) printinfo( name="miki" )

The output of the above example is:

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length Parameters

You may need a function that can handle more parameters than those specified in the original declaration. These parameters are called variable-length parameters. Unlike the two types above, they are not named in the declaration. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]

Variable names prefixed with an asterisk (*) will store all unnamed variable parameters. An example of variable-length parameters is as follows:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function definition def printinfo( arg1, *vartuple ): "Print any passed-in parameters" print "Output:" print arg1 for var in vartuple: print var return # Call the printinfo function printinfo( 10 ) printinfo( 70, 60, 50 )

The output of the above example is:

输出:
10
输出:
70
60
50

Anonymous Functions

Python uses lambda to create anonymous functions.

  • Lambda is just an expression; the function body is much simpler than def.
  • The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in a lambda expression.
  • Lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
  • Although lambda functions seem to be written in only one line, they are not equivalent to inline functions in C or C++, whose purpose is to avoid occupying stack memory when calling small functions to increase operational efficiency.

Syntax

The syntax of a lambda function contains only one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The following example:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function description sum = lambda arg1, arg2: arg1 + arg2 # Call the sum function print "The value after addition is:", sum( 10, 20 ) print "The value after addition is:", sum( 20, 20 )

The output of the above example is:

相加后的值为 :  30
相加后的值为 :  40

return Statement

The return statement [expression] exits the function and optionally returns an expression to the caller. A return statement without a parameter value returns None. The previous examples did not demonstrate how to return a value; the following example shows you how:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Function description def sum( arg1, arg2 ): # Returns the sum of 2 parameters." total = arg1 + arg2 print "Inside the function:", total return total # Call the sum function total = sum( 10, 20 )

The output of the above example is:

函数内 :  30

Variable Scope

Not all variables in a program can be accessed from any location. Access rights depend on where the variable is assigned.

The scope of a variable determines in which part of the program you can access a particular variable name. The two most basic variable scopes are as follows:
  • Global variables
  • Local variables

Global and Local Variables

Variables defined inside a function have a local scope, while those defined outside a function have a global scope.

Local variables can only be accessed inside the function in which they are declared, while global variables can be accessed throughout the entire program. When a function is called, all variable names declared within the function are added to the scope. As in the following example:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- total = 0 # This is a global variable # Function description def sum( arg1, arg2 ): # Returns the sum of 2 parameters." total = arg1 + arg2 # total is a local variable here. print "Inside the function, it is a local variable:", total return total # Call the sum function sum( 10, 20 ) print "Outside the function, it is a global variable:", total

The output of the above example is:

函数内是局部变量 :  30
函数外是全局变量 :  0
Other extensions