Home > Backend Development > Python Tutorial > Introduction to Python Basics--Function

Introduction to Python Basics--Function

巴扎黑
Release: 2017-07-21 16:45:58
Original
1918 people have browsed it

8. Function

  1. #A function is a named block of code that is used to complete specific work. def function definition, indicating the function name. When defining a function, we determine the names and positions of the parameters, and the interface definition of the function is completed. For the caller of the function, it is enough to know how to pass the correct parameters and what value the function will return. The complex logic inside the function is encapsulated. The caller need not know.

  2. To perform a specific task defined by a function, call this function. When you perform the same task multiple times in a program, you don't need to write the code to complete the task repeatedly. You only need to call the function that performs the task and let Python run the code.

  3. Higher-order function is called Higher-order function in English

8.1 Actual parameters and formal parameters

Formal parameters: Function completion information required for its work.

Actual parameters: Information passed to the function when calling the function.

8.2 Passing parameters

The function definition may contain multiple formal parameters, so the function call may also contain multiple actual parameters. There are many ways to pass actual parameters to the function. You can use positional parameters, which requires the order of the actual parameters to be the same as the order of the formal parameters.; you can also use keyword argument words, in which each actual parameter is represented by Composed of variable names and values; lists and dictionaries can also be used.

8.2.1 Positional parameters

1. When you call a function, Python must associate each actual parameter in the function call to a formal parameter in the function definition. The simple association is based on the order of the actual parameters. This association is called a positional argument.

2. In a function, you can use any number of positional arguments as needed, and Python will associate the actual parameters in the function call to the corresponding formal parameters in the function definition in order.

3. When using positional arguments to call a function, if the order of the arguments is incorrect, the output will not be correct.

8.2.2 Keyword arguments and keyword parameters

Keyword arguments are (name-value) pairs passed to the function. You associate the name and value directly in the argument, so there is no confusion when passing the argument to the function. Keyword arguments eliminate the need to worry about the order of arguments in a function call and clearly indicate the purpose of each value in the function call.

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

You can pass in any number of keyword parameters:

>>> person(' Bob', 35, city='Beijing')

name: Bob age: 35 other: {'city': 'Beijing'}

>>> person('Adam ', 45, gender='M', job='Engineer')

name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

8.2.3 Default value

When writing a function, you can specify a default value for each formal parameter. When an actual parameter is provided for a formal parameter in the calling function, Python will use the specified actual parameter value; otherwise, the default value of the formal parameter will be used. Therefore, after assigning default values ​​to formal parameters, the corresponding actual parameters can be omitted in the function call. Using default values ​​simplifies function calls and clearly indicates typical uses of the function. The biggest benefit is that it can reduce the difficulty of calling functions.

Default parameters must point to immutable objects!

##def add_end(L=None):

if L is None:

L = []

L.append('END')

return L

8.2.4 Variable parameters

Compared with defining a list or tuple parameter, defining a variable parameter only adds an * sign in front of the parameter. Inside the function, the parameter numbers receives a tuple, so the function code remains completely unchanged. However, when calling this function, any number of parameters can be passed in, including 0 parameters.

def calc(*numbers):

sum = 0

for n in numbers:

sum = sum + n * n

return sum

##>>> calc(1, 2) Python allows you to add a * sign in front of a list or tuple to turn the elements of the list or tuple into variable parameters and pass them in:

5

>>> calc()

0

>>> nums = [1, 2, 3]

*nums means passing in all elements of the nums list as variable parameters.

8.2.5 Named keyword parameters

For keyword parameters, the caller of the function can pass in any unlimited keyword parameters. As for what is passed in, you need to pass kw check inside the function.

If you want to limit the names of keyword parameters, you can use named keyword parameters. For example, only city and job are accepted as keyword parameters. The function defined in this way is as follows:

>>> calc(*nums)

14

def person(name, age, *, city, job):

print(name, age, city, job)

Unlike the keyword parameter **kw, the named keyword parameter requires a special separator *, and the parameters after * are considered for named keyword parameters.

If there is already a variable parameter in the function definition, the following named keyword parameter no longer requires a special separator*:

def person(name, age, *args, city, job):

print(name, age, args, city, job)

Named keyword parameters must be passed in the parameter name, which is different from positional parameters. If no parameter name is passed in, the call will report an error:

##>>> person('Jack', 24, 'Beijing', 'Engineer' )

Traceback (most recent call last):

File "", line 1, in

TypeError: person() takes 2 positional arguments but 4 were given

Since the parameter names city and job were missing when calling, the Python interpreter regarded these 4 parameters as positional parameters, but person () function only accepts 2 positional parameters.

Named keyword arguments can have default values ​​(default values), thus simplifying calls:

## Since the named keyword parameter city It has a default value. When calling, you do not need to pass in the city parameter:
def person(name, age, * , city='Beijing', job):

print(name, age, city, job)

>>> person('Jack', 24, job='Engineer' )# Define named keyword parameters. Don’t forget to write the separator * if there are no variable parameters. , otherwise the defined parameters will be positional parameters.

Jack 24 Beijing Engineer

8.2.5 Equivalent function calls

The output results are the same, but the calling methods are different.

Note: It doesn’t matter which calling method you use, as long as the function call produces the output you want. Just use the calling method that's easiest for you to understand.

8.2.6 Empty function (pass)

If you want to define an empty function that does nothing, you can use the pass statement:

def nop(): The pass statement does nothing, pass can be used as a placeholder For example, if you haven't figured out how to write the function code yet, you can put a pass first so that the code can run.

pass

8.2.7 Avoid actual parameter errors

No actual parameters are given, the actual parameter order is wrong, and the actual parameter format (quotation marks, etc.) is not paid attention to.

8.2.8 global statement (global variable)

If you want to modify the value stored in a global variable in a function, you must use the global statement for the variable.

8.3 Return value

A function does not always display output directly. Instead, it can process some data and return a value or a set of values. The value returned by a function is called the return value. The return value of the function is returned using the return statement.

Within a function, you can use the return statement to return a value to the line of code that called the function. Return values ​​allow you to simplify your main program by moving most of the heavy lifting of your program into functions.

8.3.1 Return multiple values

The import math statement means importing the math package, and allows subsequent code to reference sin, cos and other functions in the math package. You can return multiple values.

##>>> x, y = move(100, 100, 60, math.pi / 6)## But in fact this is just an illusion, the Python function still returns Single value:
> >> print(x, y)

151.96152422706632 70.0

##>>> r = move(100, 100, 60, math.pi / 6)> ;>> print(r)
(151.96152422706632, 70.0)

The return value is a tuple! However, syntactically, parentheses can be omitted when returning a tuple, and multiple variables can receive a tuple at the same time and assign corresponding values ​​​​according to position. Therefore, Python's function returning multiple values ​​actually returns a tuple, but it is more convenient to write. .

8.3.2 Make the actual parameter optional

Use the if statement to determine whether this actual parameter is needed.

8.3.3 Return Dictionary

The function can return any type of value, including more complex data structures such as lists and dictionaries.

8.3.4 Return function

In addition to accepting functions as parameters, higher-order functions can also return functions as result values. If you do not need to sum immediately, you can not return the summation result, but return the summation function:

##def lazy_sum(*args):

def sum():

ax = 0

for n in args:

ax = ax + n

return ax

Return sum

When we call lazy_sum(), what is returned is not the summation result, but the summation function:

##>>> f = lazy_sum(1, 3, 5, 7, 9)## When function f is called, the result of the sum is actually calculated:

>>> f

.sum at 0x101c6ed90>

##>>> f()25Note: When we call lazy_sum(), each call will return a new function, even if the same parameters are passed in:

## 

>>> f1 = lazy_sum(1, 3, 5, 7, 9)>>> f2 = lazy_sum(1, 3, 5, 7, 9)8.3.5 Combine functions with while
>>> f1==f2

False

# 

 f1() and The calling results of f2() do not affect each other.

##def get_formatted_name(first_name, last_name):

               ""Return neat name""" full_name = first_name + ' ' + last_name
return full_name.title()

while True:

print("\nPlease tell me your name:")

print("(enter 'q' at any time to quit)")

f_name = input("First name: ")

if f_name == 'q': break

l_name = input("Last name: ")

if l_name == 'q' :      

break  

formatted_name = get_formatted_name(f_name, l_name)

print("\nHello, " + formatted_name + "!")

8.3.6 Closure

One thing to keep in mind when returning a closure is: the return function should not reference any loop variables, or variables that will change subsequently. If you must refer to a loop variable, the method is to create another function and use the parameters of the function to bind the current value of the loop variable. No matter how the loop variable changes subsequently, the value bound to the function parameter will not change. The disadvantage is that the code is longer. long, you can use lambda functions to shorten the code.

def count():

def f(j):

def g():                                                                                                                                                                                                                                                                                                         i)) # f(i) is executed immediately, so the current value of i is passed into f()
return fs

>>> f1, f2, f3 = count ()

>>> f1()

1

>>> f2()

4

>>> f3()

9

8.3.7 Anonymous function lambda

When we pass in a function, sometimes there is no need to explicitly define the function. It is more convenient to pass in the anonymous function directly.

In Python, limited support is provided for anonymous functions. Still taking the map() function as an example, when calculating f(x)=x2, in addition to defining a function of f(x), you can also directly pass in an anonymous function:

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

[ 1, 4, 9, 16, 25, 36, 49, 64, 81]

## By comparison, it can be seen that the anonymous function lambda x: x * x In fact:

##def f(x): The keyword lambda represents an anonymous function, and the x before the colon represents function parameters. Anonymous functions have a limitation, that is, they can only have one expression. There is no need to write return. The return value is the result of the expression.

return x * x

There is an advantage to using anonymous functions, because the function has no name, so you don’t have to worry about function name conflicts. In addition, the anonymous function is also a function object. You can also assign the anonymous function to a variable and then use the variable to call the function:

>>> ; f = lambda x: x * x

>>> f

5)

25

8.4 Passing a list

for name in names: You will often find it useful to pass a list to a function. This list may contain names, numbers, or more complex objects. (like a dictionary). Once a list is passed to a function, the function can directly access its contents. Use functions below to improve the efficiency of processing lists.

8.4.1 Modify the list in the function

 1. After passing the list to the function, the function can modify it. Any modifications made to this list within the function are permanent, allowing you to process large amounts of data efficiently.

 2. Add or delete append pop

 3. A function completes a task, and functions can call each other. Optimize functions to facilitate maintenance and modification.

8.4.2 Forbidden to modify functions

To solve this problem, you can pass a copy of the list to the function instead of the original; in this way, any modifications made by the function will only affect the copy and not the original at all. Original.

Function_name(list_name[:]), [:] is equivalent to copying.

8.5 Pass any number of actual parameters (variable parameters)

Sometimes, you don’t know in advance how many actual parameters a function needs to accept. Fortunately, Python allows the function to collect any number of actual parameters from the calling statement. The number of arguments.

Def make_pizza(*toppings):

The asterisk in the parameter name *toppings tells Python to create an empty tuple named toppings and encapsulate all received values ​​​​in in this tuple. The print statement inside the function body generates output to demonstrate that Python can handle calling the function with one value, as well as calling the function with three values. It handles different calls in a similar way. Note that Python encapsulates the arguments into a tuple, even if the function only receives a single value.

8.5.1 Combining positional arguments and variable arguments

If you want a function to accept different types of arguments, you must accept any number of formal parameters in the function definition. Put it last. Python first matches positional arguments and keyword arguments, and then collects the remaining arguments into the last formal parameter.

8.5.2 Using variable arguments and keyword arguments

Def build_profile(first, last, **user_info):

Definition requirements of function build_profile() Provides a first and last name, while allowing the user to provide as many name-value pairs as desired. The two asterisks in the parameter **user_info tell Python to create an empty dictionary named user_info and encapsulate all name-value pairs received into this dictionary. In this function, the name-value pairs in user_info can be accessed like any other dictionary.

for key, value in user_info.items():          

profile[key] = value

user_profile = build_profile('albert', 'einstein',location=' princeton', field='physics')

8.5.3 Using parameter combinations

 1. To define a function in Python, you can use required parameters, default parameters, variable parameters, and keywords Parameters and named keyword parameters, these five parameters can be used in combination. But please note that the order of parameter definition must be: Required parameters, default parameters, variable parameters, named keyword parameters and keyword parameters.

 2. Python's functions have very flexible parameter forms, which can not only implement simple calls, but also pass in very complex parameters.

 3. The default parameters must use immutable objects. If they are variable objects, there will be logic errors when the program is running!

4. Pay attention to the syntax for defining variable parameters and keyword parameters:

5.*args is a variable parameter, and args receives a tuple;

6 .**kw is a keyword parameter, and kw receives a dict.

7. And the syntax of how to pass in variable parameters and keyword parameters when calling a function:

The variable parameters can be passed in directly: func(1, 2, 3), or You can assemble the list or tuple first, and then pass it in through *args: func(*(1, 2, 3));

The keyword parameters can be passed in directly: func(a=1, b=2 ), you can assemble the dict first and then pass it in through **kw: func(**{'a': 1, 'b': 2}).

Using *args and **kw is the idiom of Python. Of course, other parameter names can also be used, but it is best to use the idiom.

8.5.4 Recursive parameters

Within a function, other functions can be called. If a function calls itself internally, the function is recursive. The advantages of recursive functions are simple definition and clear logic. Theoretically, all recursive functions can be written in a loop, but the logic of loops is not as clear as recursion.

When using recursive functions, care must be taken to prevent stack overflow. In computers, function calls are implemented through the data structure of the stack. Whenever a function call is entered, a layer of stack frames is added to the stack. Whenever a function returns, a layer of stack frames is subtracted from the stack. Since the size of the stack is not infinite, too many recursive calls will cause stack overflow.

The movement of the Tower of Hanoi can be implemented very simply using recursive functions.

8.6 Higher-order functions

8.6.1 Higher-order functions

Since variables can point to functions and the parameters of functions can receive variables, then a function can receive another function As parameters, this kind of function is called a higher-order function.

def fact(n):

if n==1:

return 1

return n * fact(n - 1)

def add(x, y, f):

return f(x) + f(y)

8.6.2 Built-in functions

1. The function abs() that finds the absolute value has only one parameter.

 2. To determine the object type, use the type() function:

## 3. To calculate the square root, you can call math .sqrt() function.
##>>> type(123)

>>> type('str')

> >> type(None)

 4.lower() returns a lowercase string.

 5.__len__ method returns the length. In Python, if you call the len() function to try to get the length of an object, in fact, inside the len() function, it automatically calls the __len__() method of the object, so the following code is equivalent :

##>>> len('ABC') 6.max function max() can receive any number of parameters and return the largest that.
3

>>> 'ABC'.__len__()

3

7. If you want to get all the properties and methods of an object, you can use the dir() function, which returns a list containing strings. For example, to get all the properties and methods of a str object:

 8.Python’s built-in hex() function converts an integer into a string represented by hexadecimal.

 9. For class inheritance relationships, it is very inconvenient to use type(). To determine the type of class, we can use the isinstance() function. Parameter types are checked and only integer and floating point type parameters are allowed. Data type checking can be implemented using the built-in function isinstance(). Use the built-in isinstance function to determine whether a variable is a string.

 10. With getattr(), setattr() and hasattr(), we can directly manipulate the state of an object.

##>>> hasattr(obj, 'x') # Is there attribute 'x'? True Through a series of built-in functions, we can manipulate any Python object Analyze it and get its internal data. It should be noted that we will only obtain object information when we do not know the object information.  11.Python has built-in map() and reduce() functions. map applies the passed function to each element of the sequence in turn and returns the result as a new Iterator.

>>> obj.x

9

>>> hasattr(obj, 'y') # Yes Attribute 'y'?

False

>>> setattr(obj, 'y', 19) # Set an attribute 'y'

>>> hasattr( obj, 'y') # Is there an attribute 'y'?

True

>>> getattr(obj, 'y') # Get attribute 'y'

19

>> > obj.y # Get the attribute 'y'

19

##>>> def f(x):... Return x * x
.. .

>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> ; list(r)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

 reduce usage. Reduce applies a function to a sequence [x1, x2, x3, ...]. This function must receive two parameters. Reduce continues the cumulative calculation of the result with the next element of the sequence.

##>>> from functools import reduce

>>> def fn(x, y):...     return x * 10 + y

...

>>> reduce(fn, [1, 3, 5, 7, 9])

13579

 12.Python’s built-in filter() function is used to filter sequences. filter() also receives a function and a sequence . Unlike map(), filter() applies the passed function to each element in turn, and then decides to retain or discard the element based on whether the return value is True or False. The key is to correctly implement a "filter" function. Note that the filter() function returns an Iterator, which is a lazy sequence, so to force filter() to complete the calculation results, you need to use the list() function to obtain all the results and return the list.

def is_odd(n):

return n % 2 == 1

list (filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

# Result: [1, 5, 9, 15]

 13.Python’s built-in sorted() function can sort the list.

##>>> sorted([36, 5, -12, 9, -21])

[-21, -12, 5, 9, 36]

 14. The sorted() function is also a higher-order function, and it can also receive a key function to implement customization sorting, such as sorting by absolute value. To perform reverse sorting, you do not need to change the key function. You can pass in the third parameter reverse=True.

##>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) 15. Python built-in The enumerate function can turn a list into an index-element pair, so that both the index and the element itself can be iterated in a for loop.

['Zoo', 'Credit', 'bob', 'about']

 16. The round() function can return any decimal place.

8.6.3 Decorator

The way to dynamically add functionality while the code is running is called "Decorator". Essentially, a decorator is a higher-order function that returns a function. Decorator: Add new functionality without changing the function itself.

The function object has a __name__ attribute, you can get the name of the function:

##>>> def now() :## Python’s built-in @property decorator is responsible for turning a method into Attribute call:
...          print('2015-3-25')

...

>>> f = now

>>> f()

2015-3-25

>>> now.__name__

'now'

>>> f.__name__

'now'

class Student(object):

@property

def score (self):

Return self._score

@score.setter

def score(self, value):

if not isinstance(value, int):

Raise ValueError('score must be an integer!')

if value < 0 or value > 100:

raise ValueError('score must between 0 ~ 100!')

         self._score = value

 @property is widely used in class definitions, allowing callers to write short codes while ensuring necessary checks on parameters. In this way, the possibility of errors is reduced when the program is running.

The @unique decorator can help us check to ensure that there are no duplicate values.

8.7 Store functions in modules

In order to write maintainable code, you can group many functions into different files, so that the code contained in each file is relatively less. In Python, a .py file is called a module (Module).

One of the advantages of functions is that they allow you to separate blocks of code from the main program. By giving functions descriptive names, you make the main program much easier to understand. You can go one step further and store the functions in separate files called modules, and then import the modules into the main program. The import statement allows the code in the module to be used in the currently running program file.

By storing functions in separate files, you can hide the details of the program code and focus on the high-level logic of the program. This also allows you to reuse functions in many different programs. By storing functions in separate files, you can share those files with other programmers rather than the entire program. Knowing how to import functions also allows you to use function libraries written by other programmers.

In order to avoid module name conflicts, Python has introduced a method of organizing modules by directory, called a package. After the package is introduced, as long as the top-level package name does not conflict with others, all modules will not conflict with others. Now, the module name of abc.py becomes mycompany.abc, and similarly, the module name of xyz.py becomes mycompany.xyz.

Note that there will be an __init__.py file under each package directory. This file must exist. Otherwise, Python will treat this directory as a normal directory instead of a package. __init__.py can be an empty file, or it can have Python code, because __init__.py itself is a module, and its module name is mycompany.

8.7.1 Import the entire module

To make the function importable, you must first create the module. Modules are files with a .py extension that contain code to be imported into a program.

if __name__=='__main__':

test()

The first step to use a module is to import the module. When we run the hello module file on the command line, the Python interpreter sets a special variable __name__ to __main__, and if the hello module is imported elsewhere, The if judgment will fail, so this if test allows a module to execute some additional code when run through the command line, the most common is to run tests.

8.7.2 Scope

In a module, we may define many functions and variables, but some functions and variables we hope to be used by others, and some functions and variables we hope Only used inside the module. In Python, this is achieved through the _ prefix. Normal function and variable names are public and can be directly referenced, such as: abc, x123, PI, etc.; variables like __xxx__ are special variables and can be directly referenced, but have special purposes, such as the above __author__ and __name__ are special variables. The document comments defined by the hello module can also be accessed with the special variable __doc__. Generally, we should not use this variable name for our own variables; functions or variables like _xxx and __xxx are Non-public (private) should not be quoted directly, such as _abc, __abc, etc.;

Private functions or variables should not be quoted by others, so what is their use? Please see the example:

def _private_1(name):

return 'Hello, %s' % name

def _private_2(name):

return 'Hi, %s' % name

def greeting(name):

if len(name) > 3:

return _private_1(name)

else:

return _private_2(name)

We expose the greeting() function in the module and hide the internal logic with a private function. In this way, when calling the greeting() function, we don’t need to worry about the details of the internal private function. This is also a very useful code encapsulation and abstraction. method, that is: all functions that do not need to be referenced from the outside are defined as private, and only functions that need to be referenced from the outside are defined as public.

8.7.3 Import specific modules

Store multiple functions in a module, separated by commas, you can import any number of functions from the module.

8.7.4 Use as to specify an alias for a function

from pizza import make_pizza as mp

If the name of the function to be imported may conflict with an existing name in the program, Or if the function's name is too long, you can specify a short and unique alias - another name for the function, similar to a nickname. To assign this special nickname to a function, you need to do so when importing it.

8.7.5 Use as to specify an alias for the module

You can also specify an alias for the module. By giving the module a short alias (such as assigning the alias p to the pizza module), you can more easily call functions in the module. Compared to pizza.make_pizza(), p.make_pizza() is more concise.

8.7.6 Use * to import all functions in the module

Using the asterisk (*) operator allows Python to import all functions in the module.

However, when using a large module that you did not write yourself, it is best not to use this import method: if there are functions in the module with the same names as those used in your project, it may lead to unexpected results: Python may encounter multiple functions or variables with the same name and overwrite the function instead of importing all functions separately.

8.8 Function Writing Guide

When writing functions, you need to keep several details in mind.

 1. Functions should be given descriptive names and only lowercase letters and underscores should be used in them. Descriptive names help you and others understand what the code is trying to do. The above convention should also be followed when naming modules.

 2. Each function should contain a comment that briefly explains its function. The comment should follow the function definition and use the docstring format . A well-documented function allows other programmers to use it simply by reading the description in the docstring: they can trust that the code will work as described; as long as they know the name of the function, the required arguments, and the type of the return value, You can use it in your own programs.

 3.When specifying a default value for a formal parameter, there should be no spaces on either side of the equal sign.

The above is the detailed content of Introduction to Python Basics--Function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template