Home Backend Development Python Tutorial Python基础之函数用法实例详解

Python基础之函数用法实例详解

Jun 06, 2016 am 11:32 AM
python basics function usage

本文以实例形式较为详细的讲述了Python函数的用法,对于初学Python的朋友有不错的借鉴价值。分享给大家供大家参考之用。具体分析如下:

通常来说,Python的函数是由一个新的语句编写,即def,def是可执行的语句--函数并不存在,直到Python运行了def后才存在。

函数是通过赋值传递的,参数通过赋值传递给函数

def语句将创建一个函数对象并将其赋值给一个变量名,def语句的一般格式如下:

def <name>(arg1,arg2,arg3,……,argN):

  <statements>

Copy after login

def语句是实时执行的,当它运行的时候,它创建并将一个新的函数对象赋值给一个变量名,Python所有的语句都是实时执行的,没有像独立的编译时间这样的流程

由于是语句,def可以出现在任一语句可以出现的地方--甚至是嵌套在其他语句中:

if test:
  def fun():
    ...
else:
  def func():
    ...
...
func()
Copy after login

可以将函数赋值给一个不同的变量名,并通过新的变量名进行调用:

othername=func()
othername()
Copy after login

创建函数

内建的callable函数可以用来判断函数是否可调用:

>>> import math
>>> x=1
>>> y=math.sqrt
>>> callable(x)
False
>>> callable(y)
True
Copy after login

使用del语句定义函数:

>>> def hello(name):
    return 'Hello, '+name+'!'
>>> print hello('world')
Hello, world!
>>> print hello('Gumby')
Hello, Gumby!
Copy after login

编写一个fibnacci数列函数:

>>> def fibs(num):
     result=[0,1]
    for i in range(num-2):
       result.append(result[-2]+result[-1])
     return result
>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Copy after login

在函数内为参数赋值不会改变外部任何变量的值:

>>> def try_to_change(n):
    n='Mr.Gumby'
>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'
Copy after login

由于字符串(以及元组和数字)是不可改变的,故做参数的时候也就不会改变,但是如果将可变的数据结构如列表用作参数的时候会发生什么:

>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'
>>> def change(n):
     n[0]='Mr.Gumby'

>>> name=['Mrs.Entity','Mrs.Thing']
>>> change(name)
>>> name
['Mr.Gumby', 'Mrs.Thing']

Copy after login

参数发生了改变,这就是和前面例子的重要区别

以下不用函数再做一次:

>>> name=['Mrs.Entity','Mrs.Thing']
>>> n=name #再来一次,模拟传参行为
>>> n[0]='Mr.Gumby' #改变列表
>>> name
['Mr.Gumby', 'Mrs.Thing']
Copy after login

当2个变量同时引用一个列表的时候,它们的确是同时引用一个列表,想避免这种情况,可以复制一个列表的副本,当在序列中做切片的时候,返回的切片总是一个副本,所以复制了整个列表的切片,将会得到一个副本:

>>> names=['Mrs.Entity','Mrs.Thing']
>>> n=names[:]
>>> n is names
False
>>> n==names
True
Copy after login

此时改变n不会影响到names:

>>> n[0]='Mr.Gumby'
>>> n
['Mr.Gumby', 'Mrs.Thing']
>>> names
['Mrs.Entity', 'Mrs.Thing']
>>> change(names[:])
>>> names
['Mrs.Entity', 'Mrs.Thing']
Copy after login

关键字参数和默认值

参数的顺序可以通过给参数提供参数的名字(但是参数名和值一定要对应):

>>> def hello(greeting, name):
    print '%s,%s!'%(greeting, name)
>>> hello(greeting='hello',name='world!')
hello,world!!
Copy after login

关键字参数最厉害的地方在于可以在参数中给参数提供默认值:

>>> def hello_1(greeting='hello',name='world!'):
    print '%s,%s!'%(greeting,name)

>>> hello_1()
hello,world!!
>>> hello_1('Greetings')
Greetings,world!!
>>> hello_1('Greeting','universe')
Greeting,universe!

Copy after login

若想让greeting使用默认值:

>>> hello_1(name='Gumby')
hello,Gumby!
Copy after login

可以给函数提供任意多的参数,实现起来也不难:

>>> def print_params(*params):
     print params

>>> print_params('Testing')
('Testing',)
>>> print_params(1,2,3)
(1, 2, 3)

Copy after login

混合普通参数:

>>> def print_params_2(title,*params):
     print title
     print params

>>> print_params_2('params:',1,2,3)
params:
(1, 2, 3)
>>> print_params_2('Nothing:')
Nothing:
()

Copy after login

星号的意思就是“收集其余的位置参数”,如果不提供任何供收集的元素,params就是个空元组

但是不能处理关键字参数:

>>> print_params_2('Hmm...',something=42)
Traceback (most recent call last):
 File "<pyshell#112>", line 1, in <module>
  print_params_2('Hmm...',something=42)
TypeError: print_params_2() got an unexpected keyword argument 'something'
Copy after login

试试使用“**”:

>>> def print_params(**params):
     print params

>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def parames(x,y,z=3,*pospar,**keypar):
     print x,y,z
     print pospar
     print keypar

>>> parames(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> parames(1,2)
1 2 3
()
{}
>>> def print_params_3(**params):
     print params

>>> print_params_3(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> #返回的是字典而不是元组
>>> #组合‘#'与'##'
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
     print x,y,z
     print pospar
     print keypar

>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
1 2 3
()
{}
Copy after login

相信本文所述对大家Python程序设计的学习有一定的借鉴价值。

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks 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.

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.

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.

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