Introduction to Python Basics--Function
8. Function
#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.
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.
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 |
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum |
5 >>> calc() 0 |
>>> 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 " |
def person(name, age, * , city='Beijing', job): print(name, age, city, job) |
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:
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.
> >> print(x, y)151.96152422706632 70.0 | ## But in fact this is just an illusion, the Python function still returns Single value:
(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 optionalUse the if statement to determine whether this actual parameter is needed. 8.3.3 Return DictionaryThe function can return any type of value, including more complex data structures such as lists and dictionaries. 8.3.4 Return functionIn 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:
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
##def get_formatted_name(first_name, last_name): ""Return neat name"""
|
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
