Getting started with Python (11) -- functions

Posted by srirangam007 on Mon, 10 Jan 2022 21:18:44 +0100

Function is a code block with a name, which is used to complete a specific task. When the same task is executed multiple times in the program, there is no need to write repeated code blocks repeatedly, just call the function executing the task.

Declaration of function

In Python, the def keyword is used to declare functions. Each function has a function name. We call the function through the function name. The parameters passed to the function can be placed in parentheses after the function name. Of course, the function can also have no parameters. A function without parameters is called a parameterless function. The function content starts with: and the function body should be indented. After the function is executed, you can return a value to the caller through the return keyword. No return statement is equivalent to returning None. The description of the function is written below the declared function, which is called the comment of the document string. It describes the function of the function and is enclosed in three quotation marks. Python uses them to generate documents about the functions in the program. The following example demonstrates how to declare a parameterless function and call it.

def print_hello():
    """Print string“ Hello""""
    print('Hello!')

print_hello()

The output result is

Hello!

The following example demonstrates how to declare a function with two parameters and call this function.

def max(x, y):
    """Returns the larger of two numbers"""
    if x > y:
        return x
    else:
        return y

print(max(3, 7))

The result of the final program run is

7

Transfer of parameters

In Python, objects can be divided into two categories: objects that cannot be changed and objects that can be changed. In the process of passing parameters, if an unchangeable object is passed in, only the value itself is passed, and the original object will not be affected after calling the function, such as integer, string, tuple, etc. However, if a changeable object is passed in, the original object is operated. After calling the function, the modification of this object in this function is to modify the original object, such as list, dictionary, etc. Of course, the statement of unchangeable objects and changeable objects is not rigorous, and there is no such statement in the official Python documents. It is just to distinguish the objects changed when calling functions. The following example demonstrates a function call that passes an unchangeable object.

def not_change(x):
    print('id(x) = ', id(x))    # Point to the same object
    print('x = ', x)            # The value of x is the parameter value passed in
    x = 0                       # A new object was created
    print('x = ', x)            # The value of the new object is 0
    print('id(x) = ', id(x))

if __name__ == '__main__':
    y = 10
    print('id(y) = ', id(y))    # View the object id pointed to by y
    not_change(y)               # Call function
    print('y = ', y)            # The value of y does not change after the call
    print('id(y) = ', id(y))    # y also points to the object before the function is called

The output result is

id(y) =  2719015594576  # id of the object y pointed to before calling the function
id(x) =  2719015594576  # Object id pointed to by parameter
x =  10                 # Values in this object
x =  0                  # New object value
id(x) =  2719015594256  # id of the new object
y =  10                 # The value of y does not change after calling the function
id(y) =  2719015594576  # y still points to the object before the call

The following example demonstrates a function call that passes a changeable object.

def change(list):
    print('id(list) = ', id(list))  # Point to the same object
    print('list = ', list)          # The value of list is the parameter value passed in
    list.append(100)                # Operate directly on this object
    print('list = ', list)          # After the operation, the value of the list is updated
    print('id(list) = ', id(list))  # The object is still the object passed in

if __name__ == '__main__':
    x = [10, 20, 30]
    print('id(x) = ', id(x))        # View the object id pointed to by x
    change(x)                       # Call function
    print('x = ', x)                # The object pointed to by x has changed since the function was called
    print('id(x) = ', id(x))        # But the object id is still the original object

The output result is

id(x) =  2074989554688          # Object id pointed to by x before calling the function
id(list) =  2074989554688       # Object id pointed to by parameter
list =  [10, 20, 30]            # Values in this object
list =  [10, 20, 30, 100]       # Values in this object after modification
id(list) =  2074989554688       # list still points to the object just
x =  [10, 20, 30, 100]          # The object passed in is modified in the function, and the value has changed
id(x) =  2074989554688          # The id value remains unchanged

Passing arguments to a function

The methods of passing arguments to functions include positional arguments, keyword arguments, any number of arguments, etc.

Position argument

The input of location arguments must be in the same order as the parameters when the function is declared.

def print_hello(name, age):
    print(f'Hello! I am {name}, I am {age} years old.')

if __name__ == '__main__':
    name = 'Mary'
    age = 20
    print_hello(name, age)

The output result is

Hello! I am Mary, I am 20 years old.

Keyword argument

Keyword argument method can use keywords to determine the passed in parameter value when calling the function, that is, the order of parameters when calling the function can not be written in the order of declaration.

def print_hello(name, age):
    print(f'Hello! I am {name}, I am {age} years old.')

if __name__ == '__main__':
    a = 'Mary'
    b = 20
    print_hello(age=b, name=a)

The output result is

Hello! I am Mary, I am 20 years old.

Default parameters

When declaring a function, you can add the default value of the parameter after the parameter. When calling the function without giving the corresponding parameter, the default parameter will be used. Note: the default parameter must be placed last.

def print_hello(name, age = 20):
    print(f'Hello! I am {name}, I am {age} years old.')

if __name__ == '__main__':
    name = 'Mary'
    print_hello(name)

The output result is

Hello! I am Mary, I am 20 years old.

Any number of arguments

Sometimes an unknown number of parameters need to be processed in the function. When declaring the function, you can use the * sign to indicate that a parameter in the form of tuple is passed in. When calling the function, all the received values will be encapsulated in this tuple.

def print_numbers(*numbers):
    print(numbers)

if __name__ == '__main__':
    print_numbers(0, 1, 2, 3, 4, 5)

The output result is

(0, 1, 2, 3, 4, 5)

In addition, there are two asterisks with * * to indicate the input of a parameter in the form of a dictionary.

def print_keys_value(**dict):
    print(dict)

if __name__ == '__main__':
    print_keys_value(name='Mary', age=20)

The output result is

{'name': 'Mary', 'age': 20}

Return value of function

Use the return statement to specify the return value of the function. For function definitions without a return statement, Python will add return None at the end. If a return statement without a value is used, it will also return None.

def sum(*numbers):
    total = 0
    for x in numbers:
        total += x
    return total

if __name__ == '__main__':
    print(sum(0, 1, 2, 3, 4, 5))

The output result is

15

Lambda expression

In Python, you can use lambda expressions to create anonymous functions. The body of lambda is an expression, not a code block. Lambda functions cannot access parameters outside their own parameter list or in the global namespace. The format of lambda expression is lambda parameter list: expression.

sum = lambda x, y: x + y

if __name__ == '__main__':
    print(sum(4, 5))

The output result is

9

Calling functions in modules

In engineering projects, we often encounter the problem of functions with the same name, that is, there is a function with the same function name but different functions in both modules. At this time, if you want to call one of the functions, you must specify the module name. The following example demonstrates how to call functions with the same name in different modules.

# p1.py
def fuction():
    print('p1 function')
# p2.py
def fuction():
    print('p2 function')
# main.py
import p1
import p2

if __name__ == '__main__':
    p1.fuction()
    p2.fuction()

The output result is

p1 function
p2 function

We can also alias the module when importing the module and call the functions in the module through the alias.

import math as m

if __name__ == '__main__':
    print(m.fabs(-2))

Topics: Python