How To Define And Execute Customized Function In Python

Functions are well organized, reusable pieces of code that implement a single function. Function can improve the modularity of application and reuse of code. 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.

1. Define Python Function.

You can define a function that you want. Here are some simple rules.

  1. The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
  2. Any input arguments must be placed between parentheses.
  3. The first line of the function can be a string ( optional ), this string can be function description.
  4. The function body starts with a colon and is indented.
  5. Return [expression] ends the function and selectively return a value to the caller. A return without an expression will return None.
  6. By default, parameter values and parameter names are matched in the order when the function is declared.

Below is a python function example. It takes a string as an input parameter and print it to a standard display device.

def print_me( str ):
   "print input str to standard display device."
   print(str)
   return

2. Invoke Python Function.

Defining a function only gives the function a name, specifies the parameters contained in the function, and the code block structure. After the basic structure of this function is completed, you can execute it through another function call or directly from the python prompt console. Below is an example.

> print_me('hello python')

> hello python

3. Function Arguments Transfer Types.

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

3.1 Pass Function Argument Value In Order.

Pass the arguments into the function in the correct order. The number of arguments passed when a function is called must be the same as the function is defined.

For example, to call the print_me() function, you must pass in one parameter, otherwise there will be a syntax error.

> print_me()

Traceback (most recent call last):
  File "/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/python_console_progress_bar.py", line 41, in <module>
    print_me()
TypeError: print_me() missing 1 required positional argument: 'str'

3.2 Pass Function Argument Value By Argument Name.

You can also pass in function argument value by the argument name when you call the function. In this way it is allowed the order of parameters when calling a function is not consistent with that at declaration time, because the python interpreter can match parameter values with parameter names.

> print_me(str = 'hello python')

> hello python
# define a function.
def print_user( name, age ):
   
   print("Name: ", name)
   
   print("Age ", age)
   
   return

> print_user(age=100, name='Tom')

> Name:  Tom
  Age  100

3.3 Default Argument Value.

If an argument has a default value when the function is defined, so when this function is called,  if the argument value is not passed in, then it will use the default value.

In below example, the age argument has a default value 100.

# define a function. 
def print_user( name, age = 100 ): 
    print("Name: ", name) 
    print("Age ", age) 
    return 

> print_user(name='Tom') 

> Name: Tom 
  Age 100

> print_user('Jerry', 99)

> Name: Jerry
  Age 99

3.4 Pass Function Argument With *.

You may need a function that can handle more parameters than the function defined. These parameters are called indefinite length parameters. To define such type parameters, you need add a * before the parameter name when define function.

def print_args( arg1, *other_args ):
    
    print('arg1 =', arg1)
    
    for var in other_args:
       
       print(var)
    
    return

> print_args(1, 2, 3, 4, 5, 6)

>arg1 = 1
2
3
4
5
6

4. Function Arguments Data Types.

In Python, type belong to object, and variable have no type.

x ="hello python"

x =["python","java",3]

In the above code, [“python”,”java”,3] is a list type object, “hello python” is a string type object.

Variable x has no type, it is only a reference (a pointer) of an object, which can point to a list type object or point to a string type object.

4.1 Mutable And Immutable Object.

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

  1. Mutable data type example:
    # assign value [1,2,3,4] to list_1.
    list_1 = [1,2,3,4] 
    
    # change list_1[2]'s value to 5, the value of the list_1's third element is changed, but list_1 itself does not change, only part of its internal value is modified.
    list_1[2]=5
    
    when pass this kind of arguments in python function, it will pass the list object to the invoked function, and the list object outside the fun will also be affected after the modification.
    
    # define a function that will change the passed in list object value.
    def change_mutable_object( list_1 ):
       list_1.append([1,2,3,4])
       
       print("list_1 in function: ",list_1)
       
       return
    
    # create a list object.
    list_1 = ['a','b','c']
        
    print('list_1 before change_mutable_object : ', list_1)
        
    change_me(list_1)
        
    print('list_1 after change_mutable_object : ', list_1)
    
    # below are output.
    list_1 before change_mutable_object :  ['a', 'b', 'c']
    list_1 in function:  ['a', 'b', 'c', [1, 2, 3, 4]]
    list_1 after change_mutable_object :  ['a', 'b', 'c', [1, 2, 3, 4]]
    
  2. Immutable data type example:
    # create an int object with value 9. And variable x point to this object.
    x = 9
    
    # create another int object with value 100, the above int object is dropped. Then variable x point to this new object.
    x = 100
    
    # so above action do not change object value, but create new object.
    
    when pass this kind of arguments in python function, only the value of the arguments is passed, and the argument object itself is not affected. 
    
    For example, if you modify the value of a in fun (a), it only modifies another copy of object a, a itself is not modified.
    
    # define a function, in this function it will change the x value.
    def change_immmutable_object( x ):
         
        x = 100
       
        return
    
    # invoke above function.
    x = 10
        
    print('before call change_immmutable_object x :', x)
        
    change_immmutable_object(x)
        
    print('after call change_immmutable_object x :', x)
    
    # below are above source code output.
    before call change_immmutable_object x : 10
    after call change_immmutable_object x : 10
    

5. Return Statement.

Return statement [expression] exits the function and selectively returns an expression to the caller. Return statement without parameter value returns None.

# define a funciton which will return two int value's summary.
def sum( num_1, num_2 ):
   total = num_1 + num_2
   print("total in sum function : ", total)
   return total

# invoke above function.
total = sum(1, 2)
    
print('total outside sum function : ', total)

# below are output.
total in sum function :  3
total outside sum function :  3

6. Variable Scope.

All variables of a program are not accessible from all location. Access rights depend on where the variable is assigned. The scope of a variable determines which variables are accessible in which part of the program. The two most basic variable scopes are as follows.

  1. Global scope variable : Variables defined outside the function have global scope, global variables can be accessed throughout the program.
  2. Local scope variable : Variables defined within a function have a local scope, Local variables can only be accessed inside the function in which they are declared.
# this is a global variable.
total = 0

# define a function
def sum( num_1, num_2 ):
   # this total variable is a local variable.
   # it save two numbers added value.
   total = num_1 + num_2
 
   print("local variable total : ", total)

   return total
 
# invoke sum function.
sum( 10, 20 )
print("global variable total : ", total)

# below is output.
local variable total : 30
global variable total : 0

Reference

  1. How To Define Python Anonymous Function Example