一般来说,函数(function)是组织好的、可重复使用的、具有一定功能的代码段。函数能提高应用的模块性和代码的重复利用率,在Python中已经提供了很多的内建函数,比如print(),同时Python还允许用户自定义函数。
本文就来实例总结一下Python3的函数用法,具体内容如下:
一、定义
定义函数使用关键字def,后接函数名和放在圆括号( )中的可选参数列表,函数内容以冒号起始并且缩进。一般格式如下:
def 函数名(参数列表): """文档字符串""" 函数体 return [expression]
注意:参数列表可选,文档字符串可选,return语句可选。
示例:
def fib(n): """Print a Fibonacci series""" a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() fib(2000) # call f = fib # assignment f(2000)
函数名的值是一种用户自定义的函数类型。函数名的值可以被赋予另一个名字,使其也能作为函数使用。
二、函数变量作用域
在函数内部定义的变量拥有一个局部作用域,在函数外定义的拥有全局作用域。注意:在函数内部可以引用全局变量,但无法对其赋值(除非用global进行声明)。
a = 5 # 全局变量a def func1(): print('func1() print a =', a) def func2(): a = 21 # 局部变量a print('func2() print a =', a) def func3(): global a a = 10 # 修改全局变量a print('func3() print a =', a) func1() func2() func3() print('the global a =', a)
三、函数调用
1、普通调用
与其他语言中函数调用一样,Python中在调用函数时,需要给定和形参相同个数的实参并按顺序一一对应。
def fun(name, age, gender): print('Name:',name,'Age:',age,'Gender:',gender,end=' ') print() fun('Jack', 20, 'man') # call
2、使用关键字参数调用函数
函数也可以通过keyword=value 形式的关键字参数来调用,因为我们明确指出了对应关系,所以参数的顺序也就无关紧要了。
def fun(name, age, gender): print('Name:',name,'Age:',age,'Gender:',gender,end=' ') print() fun(gender='man', name='Jack', age=20) # using keyword arguments
3、调用具有默认实参的函数
Python中的函数也可以给一个或多个参数指定默认值,这样在调用时可以选择性地省略该参数:
def fun(a, b, c=5): print(a+b+c) fun(1,2) fun(1,2,3)
注意:通常情况下默认值只被计算一次,但如果默认值是一个可变对象时会有所不同, 如列表, 字典, 或大多类的对象时。例如,下面的函数在随后的调用中会累积参数值:
def fun(a, L=[]): L.append(a) print(L) fun(1) # 输出[1] fun(2) # 输出[1, 2] fun(3) # 输出[1, 2, 3]
4、调用可变参数函数
通过在形参前加一个星号(*)或两个星号(**)来指定函数可以接收任意数量的实参。
def fun(*args): print(type(args)) print(args) fun(1,2,3,4,5,6) # 输出: # <class 'tuple'> # (1, 2, 3, 4, 5, 6) def fun(**args): print(type(args)) print(args) fun(a=1,b=2,c=3,d=4,e=5) # 输出: # <class 'dict'> # {'d': 4, 'e': 5, 'b': 2, 'c': 3, 'a': 1}
从两个示例的输出可以看出:当参数形如*args时,传递给函数的任意个实参会按位置被包装进一个元组(tuple);当参数形如**args时,传递给函数的任意个key=value实参会被包装进一个字典(dict)。
5、通过解包参数调用函数
上一点说到传递任意数量的实参时会将它们打包进一个元组或字典,当然有打包也就有解包(unpacking)。通过 单星号和双星号对List、Tuple和Dictionary进行解包:
def fun(a=1, b=2, c=3): print(a+b+c) fun() # 正常调用 list1 = [11, 22, 33] dict1 = {'a':40, 'b':50, 'c':60} fun(*list1) # 解包列表 fun(**dict1) # 解包字典 # 输出: # 6 # 66 # 150
注:*用于解包Sequence,**用于解包字典。解包字典会得到一系列的key=value,故本质上就是使用关键字参数调用函数。
四、lambda表达式
lambda关键词能创建小型匿名函数。lambda函数能接收任何数量的参数但只能返回一个表达式的值,它的一般形式如下:
lambda [arg1 [,arg2,.....argn]] : expression
lambda表达式可以在任何需要函数对象的地方使用,它们在语法上被限制为单一的表达式:
f = lambda x, y: x+y print(f(10, 20)) def make_fun(n): return lambda x: x+n f = make_fun(15) print(f(5))
五、文档字符串
函式体的第一个语句可以是三引号括起来的字符串, 这个字符串就是函数的文档字符串,或称为docstring 。我们可以使用print(function.__doc__)输出文档:
def fun(): """Some information of this function. This is documentation string.""" return print(fun.__doc__)
文档字符串主要用于描述一些关于函数的信息,让用户交互地浏览和输出。建议养成在代码中添加文档字符串的好习惯。

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

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 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment