


Introduction to the basics of Python functional programming
Basic knowledge of functions
Master the basic syntax specifications and calling methods of custom functions, and master the use and calling rules of various parameters of the function.
1. Python function
- Function (Function) is an organized, reusable code segment used to implement a single or related function.
- Function can improve the modularity of the application and the reuse rate of the code.
- We have already been exposed to many built-in functions provided by Python, such as print().
- But you can also create your own functions, which are called user-defined functions.
2. Basic rules for customizing a function
You can define a function with the functions you want. The following are simple rules:
- A function code block begins with the def keyword, followed by the function identifier name and parentheses ( ).
- Any incoming parameters and independent variables must be placed between parentheses. Parameters can be defined between parentheses.
- The first line statement of a function can optionally use a documentation string - used to store function descriptions.
- The function content starts with a colon and is indented.
- returm [expression] ends the function and optionally returns a value to the caller.
- Return without expression is equivalent to returning None.
3. Customize a function syntax
Define function syntax:
def 函数标识名称(参数列表): “函数_文档字符串,对函数进行说明" 函数体 return [表达式]
By default, parameter values and parameter names are defined in the function declaration The order matches.
4. Function call
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.
The following example calls the printme ( ) function:
The output result after the call is:
4. Return keyword
- return statement [expression] exits the function and selectively returns an expression to the caller.
- The return statement without parameter value returns None.
- The previous examples did not demonstrate how to return a value. The following example tells you how to do it:
5. Parameter passing
In python, the type belongs to object, and the variable has no type:
a=[1,2,3] a="Runoob"
In the above code, [1,2,3] is List type, "Runoob" is String type, and variable a has no type Type, it is just a reference to an object (-a pointer), which can be a List type object or a String type object.
Parameter passing of Python functions
- Immutable types: Value passing in program programming, such as integers, strings, and tuples. For example, fun(a) only transfers the value of a and does not affect the a object itself. For example, modifying the value of a inside fun(a) only modifies another copied object and does not affect a itself. We often call this passing by value.
- Variable type: similar to reference passing (address passing) in programming, such as lists and dictionaries. For example, fun(la) will actually pass la. After modification, la outside fun will also be affected.
Everything in Python is an object. In a strict sense, we cannot say whether to pass by value or by reference. We should say passing immutable objects and passing mutable objects.
6. Parameters
The following are the formal parameter types that can be used when calling functions:
- Required parameters.
- Keyword parameters.
- Default parameters.
- Indefinite length parameters.
Required parameters
Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.
Example:
ch06-demo01-args-necessary.py
When calling the greeting() function, you must pass in a parameter, otherwise a syntax error will occur:
Key Word parameters
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the incoming parameter values.
Using keyword parameters allows the order of parameters when the function is called to be inconsistent with the order of declaration, because the Python interpreter can match parameter values with parameter names.
Example:
ch06-demo02-keyword.py
The following example uses the parameter name when the function printinfo() is called:
缺省参数
调用函数时,缺省参数的值如果没有传入,则被认为是默认值。
示例:
ch06-demo03-args-default.py
打印默认的age,如果age没有被传入:
注意:缺省值必须放在最后一个参数。
不定长参数*args
可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数。
适用于当参数个数不确定或根据调用情况其参数个数会动态变化的情况。
基本语法如下:
def函数名称(formal args, *args ): “函数_文档字符串" 函数体 retum [表达式]
加了星号(* )的变量名会存放所有未命名的变量参数。选择不多传参数也可,可变长参数的类型为元组。
补充: **kw
**两个型号代表接受的是一个可变长度的 字典类型的参数。
因此,改参数必须以k-v值结构出现。
def函数名称(formal _args, **kw ): “函数_文档字符串” 函数体 retum [表达式
加了星号(** )的变量名会存放所有未命名的变量参数。选择不多传参数也可,可变长参数的类型为字典。
总结: *argv和**kw的区别
两个参数必须为函数定义中参数列表中的排名最后的参数。
*argv代表该参数位置可以放任意个数的数据,最终都会转换成元组数据类型在函数体内处理。
**kw代表该参数位置可以放k=v格式的数据,最终都会转换成字典类型数据安函数体内处理。
The above is the detailed content of Introduction to the basics of Python functional programming. 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 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.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
