Details on the creation invocation and arguments of Python custom functions

  • 2020-04-02 13:27:42
  • OfStack

Functions are organized, reusable pieces of code that implement a single, or associated, function.
Functions improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
Define a function
You can define a function that you want. Here are some simple rules:

1. The function code block begins with the def keyword, followed by the function identifier name and parenthesis ().
2. Any incoming arguments and arguments must be placed between parentheses. Parameters can be defined between parentheses.
The first line of a function can optionally use a docstring -- to hold the function description.
4. The function begins with a colon and is indented.
5.Return[expression] closes the function, optionally returning a value to the caller. A return without an expression returns None.

grammar

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.

The instance

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

def printme( str ):
   " Prints the incoming string to the standard display device "
   print str
   return

Second, function call
Defining a function gives the function only a name, specifies the parameters that the function contains, and specifies the code block structure. Once the basic structure of this function is complete, you can execute it from another function call or directly from a Python prompt.

The following example calls the printme () function:

#!/usr/bin/python

# Function definition is here
def printme( str ):
   " Print any incoming string "
   print str;
   return;

# Now you can call printme function
printme(" I'm going to call a user-defined function !");
printme(" Call the same function again ");
# Output results of the above examples: 
# I'm going to call a user-defined function !
# Call the same function again 

Pass parameters by value and by reference
All arguments (arguments) are passed by reference in Python. If you change the argument in the function, the original argument is changed in the function that calls the function. Such as:

#!/usr/bin/python

#  Writable function description 
def changeme( mylist ):
   " Modify the incoming list "
   mylist.append([1,2,3,4]);
   print " Value inside the function : ", mylist
   return

#  call changeme function 
mylist = [10,20,30];
changeme( mylist );
print " Value outside the function : ", mylist
# The object passing in a function USES the same reference as the object adding new content at the end. Therefore, the output results are as follows: 
# Value inside the function :  [10, 20, 30, [1, 2, 3, 4]]
# Value outside the function :  [10, 20, 30, [1, 2, 3, 4]]

Function parameters
Types of arguments that Python functions can use:

1. Required parameters
2. Name parameters
3. Default parameters
4. Variable length parameters

1. Necessary parameters

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.
To call the printme() function, you must pass in an argument, or you'll get a syntax error:

#!/usr/bin/python

# Writable function description 
def printme( str ):
   " Print any incoming string "
   print str;
   return;

# call printme function 
printme();
# Output results of the above examples: 
#Traceback (most recent call last):
#  File "test.py", line 11, in <module>
#    printme();
#TypeError: printme() takes exactly 1 argument (0 given)


2. Named parameters

Named parameters are closely related to the function call, and the caller USES the name of the parameter to determine the value of the parameter passed in. You can skip unpassed arguments or random arguments, because the Python interpreter can match arguments with their names. Call the printme() function with a named parameter:

#!/usr/bin/python

# Writable function description 
def printme( str ):
   " Print any incoming string "
   print str;
   return;

# call printme function 
printme( str = "My string");
# Output results of the above examples: 
#My string

The following example can show more clearly that the order of named parameters is not important:
#!/usr/bin/python

# Writable function description 
def printinfo( name, age ):
   " Print any incoming string "
   print "Name: ", name;
   print "Age ", age;
   return;

# call printinfo function 
printinfo( age=50, name="miki" );
# Output results of the above examples: 
#Name:  miki
#Age  50


3. Default parameters

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

#!/usr/bin/python

# Writable function description 
def printinfo( name, age = 35 ):
   " Print any incoming string "
   print "Name: ", name;
   print "Age ", age;
   return;

# call printinfo function 
printinfo( age=50, name="miki" );
printinfo( name="miki" );
# Output results of the above examples: 
#Name:  miki
#Age  50
#Name:  miki
#Age  35

4. Variable length parameters

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

def functionname([formal_args,] *var_args_tuple ):
   " function _ docstring "
   function_suite
   return [expression]

The variable name with the asterisk (*) will hold all the unnamed variable arguments. Select not to pass parameters can also be. The following example:
#!/usr/bin/python

#  Writable function description 
def printinfo( arg1, *vartuple ):
   " Print any incoming parameters "
   print " The output : "
   print arg1
   for var in vartuple:
      print var
   return;

#  call printinfo  function 
printinfo( 10 );
printinfo( 70, 60, 50 );
# Output results of the above examples: 
# The output :
#10
# The output :
#70
#60
#50

5. Anonymous functions
Using lambda keywords allows you to create small anonymous functions. This function gets its name from the omission of the standard procedure for declaring functions with def.

Lambda functions can take any number of arguments but can only return the value of one expression, and can only contain commands or multiple expressions.
Anonymous functions cannot call print directly, because lambda requires an expression.
Lambda functions have their own namespace and cannot access arguments outside of their own argument list or in the global namespace.
While lambda functions look like they can only be written on one line, they are not the same as inline functions in C or C++, which are designed to increase efficiency by calling small functions without taking up stack memory.
grammar

The syntax of lambda functions consists of only one statement, as follows:

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

The following example:
#!/usr/bin/python

# Writable function description 
sum = lambda arg1, arg2: arg1 + arg2;

# call sum function 
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
# Output results of the above examples: 
#Value of total :  30
#Value of total :  40

About return statements
The return statement [expression] exits a function, optionally returning an expression to the caller. The return statement with no parameter value returns None. The previous examples don't show you how to return a value, but the following example shows you how:

#!/usr/bin/python

#  Writable function description 
def sum( arg1, arg2 ):
   #  return 2 The sum of two parameters ."
   total = arg1 + arg2
   print "Inside the function : ", total
   return total;

#  call sum function 
total = sum( 10, 20 );
print "Outside the function : ", total 
# Output results of the above examples: 
#Inside the function :  30
#Outside the function :  30


Variable scope
All the variables in a program are not accessible everywhere. Access depends on where the variable is assigned.

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

Variables and local variables
Variables defined inside functions have a local scope, and variables defined outside functions have a global scope.

Local variables can only be accessed within their declared functions, while global variables can be accessed programmatically. When a function is called, all variable names declared in the function are added to the scope. The following example:

#!/usr/bin/python

total = 0; # This is global variable.
#  Writable function description 
def sum( arg1, arg2 ):
   # return 2 The sum of two parameters ."
   total = arg1 + arg2; # total In this case, local variables .
   print "Inside the function local total : ", total
   return total;

# call sum function 
sum( 10, 20 );
print "Outside the function global total : ", total 
# Output results of the above examples: 
#Inside the function local total :  30
#Outside the function global total :  0


Related articles: