Home Backend Development Python Tutorial Detailed explanation of the use of Python functions

Detailed explanation of the use of Python functions

Mar 23, 2017 pm 02:33 PM
python function

1. Basic definition of function


def 函数名称(参数)
         执行语        
         return 返回值
Copy after login

def: Keyword to define the function;

Function name: As the name suggests, It is the name of the function. It can be used to call the function. Keywords cannot be used to name it. It is best to name it with the English name of the function. Camel case and underline methods can be used;

Parameters: used to give The function provides data, with distinction between formal parameters and actual parameters;

Execution statement: also called function body, used to perform a series of logical operations;

Return value: After executing the function, return The data given to the caller defaults to None, so when there is no return value, you do not need to write return.

2. Ordinary parameters of the function

The most direct one-to-one relationship parameters, such as:


def fun_ex(a,b):            #a,b是函数fun_ex的形式参数,也叫形参
    sum=a+b    print('sum =',sum)
fun_ex(1,3)                  #1,3是函数fun_ex的实际参数,也叫实参#运行结果sum = 4
Copy after login

3. Default parameters of the function

Define a default value for the parameter. If no parameters are specified when the function is called, then The function uses default parameters, which need to be placed at the end of the parameter list, such as:


def fun_ex(a,b=6):    #默认参数放在参数列表最后,如b=6只能在a后面
    sum=a+b    print('sum =',sum)
fun_ex(1,3)
fun_ex(1)#运行结果sum = 4sum = 7
Copy after login

4. Dynamic parameters of the function

There is no need to specify whether the parameter is a tuple or dictionary, the function automatically converts it into a tuple or dictionary, such as:

#转换成元组的动态参数形式,接受的参数需要是可以转成元组的形式,就是类元组形式的数据,如数值,列表,元组。

def func(*args):
    print(args,type(args))

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

date_ex1=('a','b','c','d')
func(*date_ex1)

#运行结果
(1, 2, 3, 4, 5) <class &#39;tuple&#39;>
('a', 'b', 'c', 'd') <class &#39;tuple&#39;>

动态参数形式一
Copy after login
#转换成字典的动态参数形式,接收的参数要是能转换成字典形式的,就是类字典形式的数据,如键值对,字典

def func(**kwargs):
    print(kwargs,type(kwargs))

func(a=11,b=22)

date_ex2={'a':111,'b':222}
func(**date_ex2)

#运行结果
{'b': 22, 'a': 11} <class &#39;dict&#39;>
{'b': 222, 'a': 111} <class &#39;dict&#39;>

动态参数形式二
Copy after login
#根据传的参数转换成元组和字典的动态参数形式,接收的参数可以是任何形式。
def func(*args,**kwargs):
    print(args, type(args))
    print(kwargs,type(kwargs))

func(123,321,a=999,b=666)

date_ex3={'a':123,'b':321}
func(**date_ex3)

#运行结果
(123, 321) <class &#39;tuple&#39;>
{'b': 666, 'a': 999} <class &#39;dict&#39;>
() <class &#39;tuple&#39;>
{'b': 321, 'a': 123} <class &#39;dict&#39;>

动态参数形式三
Copy after login

5. The return value of the function

When running a function, you generally need to get some information from it. In this case, you need to use return to get the return value, such as:

def fun_ex(a,b):
    sum=a+b
    return sum      #返回sum值

re=fun_ex(1,3)   
print('sum =',re)

#运行结果
sum = 4
Copy after login

6.lambda The expression

is used to express simple functions, such as:

#普通方法定义函数
def sum(a,b):
    return a+b
sum=sum(1,2)
print(sum)

#lambda表达式定义函数
myLambda = lambda a,b : a+b
sum=myLambda(2,3)
print(sum)

#运行结果
5
Copy after login


7. Built-in functions

1) Built-in functions List

    Built-in Functions    
<span class="pre">abs()</span> <span class="pre">dict()</span> <span class="pre">help()</span> <span class="pre">min()</span> <span class="pre">setattr()</span>
<span class="pre">all()</span> <span class="pre">dir()</span> <span class="pre">hex()</span> <span class="pre">next()</span> <span class="pre">slice()</span>
<span class="pre">any()</span> <span class="pre">pmod()</span> <span class="pre">id()</span> <span class="pre">object()</span> <span class="pre">sorted()</span>
<span class="pre">ascii()</span> <span class="pre">enumerate()</span> <span class="pre">input()</span> <span class="pre">oct()</span> <span class="pre">staticmethod()</span>
<span class="pre">bin()</span> <span class="pre">eval()</span> <span class="pre">int()</span> <span class="pre">open()</span> <span class="pre">str()</span>
<span class="pre">bool()</span> <span class="pre">exec()</span> <span class="pre">isinstance()</span> <span class="pre">ord()</span> <span class="pre">sum()</span>
<span class="pre">bytearray()</span> <span class="pre">filter()</span> <span class="pre">issubclass()</span> <span class="pre">pow()</span> <span class="pre">super()</span>
<span class="pre">bytes()</span> <span class="pre">float()</span> <span class="pre">iter()</span> <span class="pre">print()</span> <span class="pre">tuple()</span>
<span class="pre">callable()</span> <span class="pre">format()</span> <span class="pre">len()</span> <span class="pre">property()</span> <span class="pre">type()</span>
<span class="pre">chr()</span> <span class="pre">frozenset()</span> <span class="pre">list()</span> <span class="pre">range()</span> <span class="pre">vars()</span>
<span class="pre">classmethod()</span> <span class="pre">getattr()</span> <span class="pre">locals()</span> <span class="pre">repr()</span> <span class="pre">zip()</span>
<span class="pre">compile()</span> <span class="pre">globals()</span> <span class="pre">map()</span> <span class="pre">reversed()</span> <span class="pre">__import__()</span>
<span class="pre">complex()</span> <span class="pre">hasattr()</span> <span class="pre">max()</span> <span class="pre">round()</span>  
<span class="pre">delattr()</span> <span class="pre">hash()</span> <span class="pre">memoryview()</span> <span class="pre">set()</span>  

 

The above is the detailed content of Detailed explanation of the use of Python functions. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Introduction to Python functions: Usage and examples of isinstance function Introduction to Python functions: Usage and examples of isinstance function Nov 04, 2023 pm 03:15 PM

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows

Introduction to Python functions: Usage and examples of abs function Introduction to Python functions: Usage and examples of abs function Nov 03, 2023 pm 12:05 PM

Introduction to Python functions: usage and examples of the abs function 1. Introduction to the usage of the abs function In Python, the abs function is a built-in function used to calculate the absolute value of a given value. It can accept a numeric argument and return the absolute value of that number. The basic syntax of the abs function is as follows: abs(x) where x is the numerical parameter to calculate the absolute value, which can be an integer or a floating point number. 2. Examples of abs function Below we will show the usage of abs function through some specific examples: Example 1: Calculation

How to fix hardcoded errors in Python's functions? How to fix hardcoded errors in Python's functions? Jun 25, 2023 pm 08:15 PM

With the widespread use of the Python programming language, developers often encounter the problem of "hard-coded errors" in the process of writing programs. The so-called "hard coding error" refers to writing specific numerical values, strings and other data directly into the code instead of defining them as constants or variables. This approach has many problems, such as low readability, difficulty in maintaining, modifying and testing, and it also increases the possibility of errors. This article discusses how to solve the problem of hard-coded errors in Python functions. 1. What is hard

Introduction to Python functions: functions and examples of filter functions Introduction to Python functions: functions and examples of filter functions Nov 04, 2023 am 10:13 AM

Introduction to Python functions: The role and examples of the filter function Python is a powerful programming language that provides many built-in functions, one of which is the filter function. The filter function is used to filter the elements in the list and return a new list composed of elements that meet the specified conditions. In this article, we will introduce what the filter function does and provide some examples to help readers understand its usage and potential. The syntax of the filter function is as follows: filter(function

Introduction to Python functions: usage and examples of dir function Introduction to Python functions: usage and examples of dir function Nov 03, 2023 pm 01:28 PM

Introduction to Python functions: Usage and examples of dir function Python is an open source, high-level, interpreted programming language. It can be used to develop various types of applications, including web applications, desktop applications, games, etc. Python provides a large number of built-in functions and modules that can help programmers write efficient Python code quickly. Among them, the dir function is a very useful built-in function, which can help programmers view the properties and methods in objects, modules or classes.

Introduction to Python functions: functions and usage examples of globals functions Introduction to Python functions: functions and usage examples of globals functions Nov 04, 2023 pm 02:58 PM

Introduction to Python functions: functions and usage examples of the globals function Python is a powerful programming language that provides many built-in functions, among which the globals() function is one of them. This article will introduce the functions and usage examples of the globals() function, with specific code examples. 1. Functions of the globals function The globals() function is a built-in function that returns a dictionary of global variables of the current module. It returns a dictionary containing global variables, where

How to resolve unsafe concurrency errors in Python functions? How to resolve unsafe concurrency errors in Python functions? Jun 24, 2023 pm 12:37 PM

Python is a popular high-level programming language with simple and easy-to-understand syntax, rich standard library and open source community support. It also supports multiple programming paradigms, such as object-oriented programming, functional programming, etc. In particular, Python is widely used in data processing, machine learning, scientific computing and other fields. However, Python also has some problems in multi-threaded or multi-process programming. One of them is concurrency insecurity. This article will introduce how to solve concurrency concerns in Python functions from the following aspects:

Introduction to Python functions: introduction and examples of range function Introduction to Python functions: introduction and examples of range function Nov 04, 2023 am 10:10 AM

Introduction to Python functions: Introduction and examples of range functions Python is a high-level programming language widely used in various fields. It is easy to learn and has a rich built-in function library. Among them, the range function is one of the commonly used built-in functions in Python. This article will introduce the function and usage of the range function in detail, and demonstrate its specific application through examples. The range function is a function used to generate an integer sequence. It accepts three parameters, which are the starting value (

See all articles