Python function

A function is a well-organized, reusable piece of code that is used to implement a single, or associated function.

functions can improve the modularity of the application and the reuse of code. You already know that Python provides a lot of built-in functions, such as print(). But you can also create functions yourself, which is called a user-defined function.


Define a function

You can define a function that you want to function. Here are the simple rules:

  • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
  • Any incoming parameters and arguments must be placed between the parentheses. Parentheses can be used to define parameters.
  • The first line of the function can optionally use a docstring—for storing function descriptions.
  • The function content starts with a colon and is indented.
  • return [expression] Ends the function, optionally returning a value to the caller. A return without an expression is equivalent to returning None.

Syntax

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

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

Instance

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

Instance (Python 2.0+)

def printme ( str ): "Print incoming strings onto standard display devices" print str return

Function call

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

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

The following example calls the printme() function:

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #definition function def printme( str ): "Print any incoming strings " print str; return; # calling function printme("I want to call a user-defined function!"); printme("call the same function again");

The output of the above example:

Parameter passing

In Python, types are objects, and variables are of no type:

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

In the above code, [1,2,3] is a List type, "WELOOKUPS" is a String type, and the variable a is of no type, she is just a A reference to an object (a pointer), either a List type object or a String type object.

mutable and immutable objects

In Python, strings, tuples, and numbers are unchangeable objects, while list, dict, etc. are objects that can be modified.

  • Immutable type: variable assignment a=5 and then assign a=10, here is actually a new int value object 10, then let a point to it , and 5 is discarded, not changing the value of a, which is equivalent to newly generating a.

  • Variable type: variable assignment la=[1,2,3,4] and then assign la[2]=5 is the list la The third element value changes, itself la does not move, only a part of its internal value is modified.

Parameter passing of python functions:

  • Immutable types: are similar to c++ value passing, such as integers, strings, tuples. For fun(a), only the value of a is passed, which does not affect the a object itself. For example, modifying the value of a inside fun(a) simply changes another copied object without affecting a itself.

  • Variable types: are similar to c++'s reference passing, such as lists, dictionaries. For example, fun(la), the la is actually passed, and the la outside the modified fun will also be affected

Everything in Python is an object. Strictly speaking, we can't say value passing or reference passing. We should say passing immutable objects and passing variable objects.

python pass immutable object instance

Instance(Python 2.0+)

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

The instance has an int object 2, and the variable pointing to it is b. When passed to the ChangeInt function, the variable b is copied by value, and both a and b point to the same Int object, when a=10 , then generate an int value object 10 and let a point to it.

Transfer variable object instance

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Writable function description def changeme( mylist ): "Modify the incoming list" mylist.append([1,2,3,4]); print "Function value: ", mylist return # Call the changeme function mylist = [10,20,30]; changeme( mylist ); print "Out-of-function value: ", mylist

The input function in the instance and the object that adds new content at the end use the same reference, so the output is as follows:

Function value: [10, 20, 30, [1, 2, 3, 4]]
Out-of-function value: [10, 20, 30, [1, 2, 3, 4]]

parameters

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

  • Required parameters
  • Keyword parameters
  • Default parameters
  • Indefinite length parameter

Required parameters

Required parameters must be passed to the function in the correct order. The number of calls must be the same as when they were declared.

Invoke the printme() function, you must pass in a parameter, or a syntax error will occur:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #Writable function description def printme( str ): "Print any incoming string" print str; return; #Call the printme function printme();

The output of the above example:

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

Keyword parameters

Keyword parameters are closely related to function calls. Function calls use keyword arguments to determine the value of the passed argument.

Using keyword arguments allows the order of arguments to be inconsistent with the declaration time, because the Python interpreter can match parameter values with parameter names.

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

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #Writable function description def printme( str ): "Print any incoming string" print str; return; #Call the printme function printme( str = "My string");

The output of the above example:

My string

The following example shows the order of keyword arguments as unimportant:

Instance(Python 2.0+)

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

The output of the above example:

Name: miki
Age 50

Default parameter

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

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #writable function description def printinfo( name, age = 35 ): "Print any incoming strings " 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:

Name: miki
Age 50
Name: miki
Age 35

indefinite length parameter

You may need a function that can handle more parameters than when you originally declared it. These parameters are called indefinite length parameters, which are different from the above two parameters and are not named when they are declared. The basic syntax is as follows:

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

A variable name with an asterisk (*) will hold all unnamed variable parameters. Examples of variable length parameters are as follows:

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # writable function description def printinfo( arg1, *vartuple ): "Print any incoming 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:

Output:
10
Output:
70
60
50

Anonymous function

python uses lambda to create anonymous functions.

  • lambda is just an expression, and the function body is much simpler than def.
  • The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.
  • The lambda function has its own namespace and cannot access parameters outside of its own parameter list or in the global namespace.
  • Although the lambda function seems to be able to write only one line, it is not equivalent to C or C++ inline functions. The purpose of the latter is to call the small function without occupying the stack memory and increasing the running efficiency.

Syntax

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

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

Example below:

Instance(Python 2.0+)

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

The output of the above example:

The added value is  : 30
Added values : 40

return statement

return statement [expression] exits the function, optionally returning an expression to the caller. A return statement with no parameter value returns None. The previous examples have not shown how to return a value. The following example tells you what to do:

Instance(Python 2.0+)

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

The output of the above example:

Function within : 30

Variable Scope

All variables of a program are not accessible at any location. Access rights depend on where the variable is assigned.

The scope of the variable determines which part of the program you can access for which 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 and are defined outside the function with a global scope.

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

Instance(Python 2.0+)

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

The above example output:

Local variable : 30
Outside the function is a global variable : 0





welookups is optimized for learning.© welookups .
All Right Reserved and you agree to have read and accepted our term and condition