Functions in Python

Posted by watsmyname on Wed, 19 Jan 2022 18:25:36 +0100

catalogue

1. Define function

2. Transfer parameters

2.1} parameter type

2.1.1} location arguments

2.1.2} keyword arguments

2.1.3 # delivery list

2.2} passing any number of arguments

3. Return value

4) store functions in modules

4.1} import module

4.2} import specific functions

4.3} use as to specify alias

1. Define function

The following is a simple function for printing greetings, called greet_user():

def greet_user():
    """Show simple greetings"""
    print("hello!")

greet_user()

Among them, we use the def keyword to define a function (indicate the function name to Python, and possibly pass in parameters in parentheses), which ends with a colon. Follow def greet_ All contractions after user() form the function body, in which the three quotation marks "" "" "" are the comments of the document string

2 transfer parameters

2.1} parameter type

There are three main ways to pass arguments to functions: (1) position arguments, which requires that the order of arguments is the same as that of formal parameters; (2) Keyword arguments, where each argument is composed of variable name and value; (3) You can also use lists and dictionaries

2.1.1} location arguments

The order of position arguments is required to be the same as that of formal parameters. An example is given below:

def describe_pet(animal_type, pet_name):
    """Display pet information"""
    print(f"\nI have a {animal_type}")
    print(f"My {animal_type}'s name is {pet_name.title()}")

describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

2.1.2} keyword arguments

Keyword arguments are name value pairs passed to the function, so they do not need to consider the order of arguments in the function call. The following is an example of keyword arguments based on the functions given above:

describe_pet(pet_name = 'harry', animal_type = 'hamster')

Python can also set the default value for the function, that is, when defining the function, the formal parameter will be assigned. After that, if the user does not specify a new argument value, the function will always default to the default value. Examples are as follows:

def describe_pet(animal_type = 'dog', pet_name):
    """Pet information is displayed, and the default pet type here is dog"""
    ...

# Only pass in pet when calling a function_ Name
describe_pet(pet_name = 'willie')

# If a new animal is passed in_ Type argument, the newly passed in argument shall prevail
describe_pet(animal_type = 'cat', pet_name = 'ali')

2.1.3 # delivery list

It is useful to pass a list to a function, which may contain names, numbers, or more complex objects (such as dictionaries). After passing the list to the function, the function can directly access its contents.

1. Modify the list in the function

After passing the list to the function, the function can be aligned and modified, and the modification is permanent. The following is an example:

def print_models(unprinted_designs, completed_models):
    """
    Simulate printing each design until there are no unprinted designs.
    After printing each design, move it to the list completed_models Yes.
    """
    
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"Printing model: {current_design}")
        completed_models.append(current_design)

unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_designs = []

print_models(unprinted_designs, completed_designs)

2. Prohibited function modification list

Sometimes we need to prohibit functions from modifying the list. To solve this problem, we can pass a copy of the list to the function instead of the original. Any changes made to this function only affect the copy, and the original is not affected at all.

To pass a copy of the list to the function, you can use the slice notation [:], as shown in the following example:

function_name(list_name[:])

2.2} passing any number of arguments

When we don't know how many arguments a function needs to accept, we can use the method provided in Python to collect any number of arguments.

As an example, the asterisk in the formal parameter name * toppings , allows Python to create an empty ancestor named toppings and encapsulate all received values into this tuple:

def make_pizza(*toppings):
    ...

make_pizza('pepperoni')
make_pizza('mushroom', 'green peppers', 'extra cheese')

tips:  

1. If you want the function to accept different types of arguments, you must put the formal parameters that accept any number of arguments last in the function definition. Python first matches the position arguments and keyword arguments, and then collects the remaining arguments into the last formal parameter.

2. If the function needs to accept any number of key value pairs, you can use the double asterisk * * to let Python create an empty dictionary and put all the received name value pairs into this dictionary.

3. Return value

Function can return any type of value, including complex data structures such as lists and dictionaries

The following is an example:

def build-person(first_name, last_name):
    """Returns a dictionary containing information about a person's name"""
    person = {'first_name': first_name, 'last_name': last_name}
    return person 

4) store functions in modules

One of the advantages of using functions is that code blocks can be separated from the main program. By assigning descriptive names to functions, the main program can be much easier to understand. At the same time, we can further store the function in a separate file called module, and then import the module into the main program.

4.1} import module

To make the function importable, you must first create a module. The module has an extension of py file containing the code to be imported into the program.

One import method is to write an import statement and specify the module name in it to use all the functions in the module in the program. The following example: add pizza Py import making_ pizza. Py (the code in making_pizza.py is shown below)

import pizza

pizza.make_pizza(16, 'pepper')

4.2} import specific functions

We can also import specific functions. The import method syntax is as follows:

from module_name import function_name

You can also import any number of functions:

from module_name import function_0, function_1, function_2

Use the asterisk (*) to import all functions in the module:

from module_name import *

4.3} use as to specify alias

1. Use as to assign an alias to the function

If the function name to be imported may conflict with the existing name in the program, or the function name is too long, we can specify a short and unique alias.

How to rename a function using the keyword as:

from module_name import function_name as new_name 

2. Use as to assign an alias to the module

We can also use as to assign an alias to the module, which makes it easier for us to call the methods in the module.

How to rename a module using the keyword as:

import module_name as new_name

Topics: Python