Home Backend Development Python Tutorial Python3基础之函数用法

Python3基础之函数用法

Jun 16, 2016 am 08:42 AM
python3 function Base usage

一般来说,函数(function)是组织好的、可重复使用的、具有一定功能的代码段。函数能提高应用的模块性和代码的重复利用率,在Python中已经提供了很多的内建函数,比如print(),同时Python还允许用户自定义函数。

本文就来实例总结一下Python3的函数用法,具体内容如下:

一、定义

定义函数使用关键字def,后接函数名和放在圆括号( )中的可选参数列表,函数内容以冒号起始并且缩进。一般格式如下:

def 函数名(参数列表): 
  """文档字符串""" 
  函数体 
  return [expression] 
Copy after login

注意:参数列表可选,文档字符串可选,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) 
Copy after login

函数名的值是一种用户自定义的函数类型。函数名的值可以被赋予另一个名字,使其也能作为函数使用。

二、函数变量作用域

在函数内部定义的变量拥有一个局部作用域,在函数外定义的拥有全局作用域。注意:在函数内部可以引用全局变量,但无法对其赋值(除非用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) 

Copy after login

三、函数调用

1、普通调用

与其他语言中函数调用一样,Python中在调用函数时,需要给定和形参相同个数的实参并按顺序一一对应。

def fun(name, age, gender): 
  print('Name:',name,'Age:',age,'Gender:',gender,end=' ') 
  print() 
 
fun('Jack', 20, 'man') # call 
Copy after login


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 

Copy after login

3、调用具有默认实参的函数

Python中的函数也可以给一个或多个参数指定默认值,这样在调用时可以选择性地省略该参数:

def fun(a, b, c=5): 
  print(a+b+c) 
 
fun(1,2) 
fun(1,2,3) 

Copy after login

注意:通常情况下默认值只被计算一次,但如果默认值是一个可变对象时会有所不同, 如列表, 字典, 或大多类的对象时。例如,下面的函数在随后的调用中会累积参数值

def fun(a, L=[]): 
  L.append(a) 
  print(L) 
 
fun(1) # 输出[1] 
fun(2) # 输出[1, 2] 
fun(3) # 输出[1, 2, 3] 

Copy after login

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} 

Copy after login

从两个示例的输出可以看出:当参数形如*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 

Copy after login

注:*用于解包Sequence,**用于解包字典。解包字典会得到一系列的key=value,故本质上就是使用关键字参数调用函数。

四、lambda表达式

lambda关键词能创建小型匿名函数。lambda函数能接收任何数量的参数但只能返回一个表达式的值,它的一般形式如下:

lambda [arg1 [,arg2,.....argn]] : expression 
Copy after login

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)) 

Copy after login

五、文档字符串

函式体的第一个语句可以是三引号括起来的字符串, 这个字符串就是函数的文档字符串,或称为docstring 。我们可以使用print(function.__doc__)输出文档:

def fun(): 
  """Some information of this function. 
  This is documentation string.""" 
  return 
 
print(fun.__doc__) 

Copy after login

文档字符串主要用于描述一些关于函数的信息,让用户交互地浏览和输出。建议养成在代码中添加文档字符串的好习惯。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles