search
HomeBackend DevelopmentPython TutorialDetailed explanation of the use of Python functions

1. Basic definition of function


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

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

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

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;>
(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;) <class &#39;tuple&#39;>

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

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

func(a=11,b=22)

date_ex2={&#39;a&#39;:111,&#39;b&#39;:222}
func(**date_ex2)

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

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

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

date_ex3={&#39;a&#39;:123,&#39;b&#39;:321}
func(**date_ex3)

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

动态参数形式三

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(&#39;sum =&#39;,re)

#运行结果
sum = 4

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


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
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
Understanding the Difference: For Loop and While Loop in PythonUnderstanding the Difference: For Loop and While Loop in PythonMay 16, 2025 am 12:17 AM

ThedifferencebetweenaforloopandawhileloopinPythonisthataforloopisusedwhenthenumberofiterationsisknowninadvance,whileawhileloopisusedwhenaconditionneedstobecheckedrepeatedlywithoutknowingthenumberofiterations.1)Forloopsareidealforiteratingoversequence

Python Loop Control: For vs While - A ComparisonPython Loop Control: For vs While - A ComparisonMay 16, 2025 am 12:16 AM

In Python, for loops are suitable for cases where the number of iterations is known, while loops are suitable for cases where the number of iterations is unknown and more control is required. 1) For loops are suitable for traversing sequences, such as lists, strings, etc., with concise and Pythonic code. 2) While loops are more appropriate when you need to control the loop according to conditions or wait for user input, but you need to pay attention to avoid infinite loops. 3) In terms of performance, the for loop is slightly faster, but the difference is usually not large. Choosing the right loop type can improve the efficiency and readability of your code.

How to Combine Two Lists in Python: 5 Easy WaysHow to Combine Two Lists in Python: 5 Easy WaysMay 16, 2025 am 12:16 AM

In Python, lists can be merged through five methods: 1) Use operators, which are simple and intuitive, suitable for small lists; 2) Use extend() method to directly modify the original list, suitable for lists that need to be updated frequently; 3) Use list analytical formulas, concise and operational on elements; 4) Use itertools.chain() function to efficient memory and suitable for large data sets; 5) Use * operators and zip() function to be suitable for scenes where elements need to be paired. Each method has its specific uses and advantages and disadvantages, and the project requirements and performance should be taken into account when choosing.

For Loop vs While Loop: Python Syntax, Use Cases & ExamplesFor Loop vs While Loop: Python Syntax, Use Cases & ExamplesMay 16, 2025 am 12:14 AM

Forloopsareusedwhenthenumberofiterationsisknown,whilewhileloopsareuseduntilaconditionismet.1)Forloopsareidealforsequenceslikelists,usingsyntaxlike'forfruitinfruits:print(fruit)'.2)Whileloopsaresuitableforunknowniterationcounts,e.g.,'whilecountdown>

Python concatenate list of listsPython concatenate list of listsMay 16, 2025 am 12:08 AM

ToconcatenatealistoflistsinPython,useextend,listcomprehensions,itertools.chain,orrecursivefunctions.1)Extendmethodisstraightforwardbutverbose.2)Listcomprehensionsareconciseandefficientforlargerdatasets.3)Itertools.chainismemory-efficientforlargedatas

Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!