您的位置:首页 > 编程语言 > Python开发

Python中函数的定义和实现

2018-01-02 16:48 543 查看
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数

最简单的函数实现,可以敲敲试试,体验一下。

>>> def FirstFunc():
print("First Function!")
print("Life is short,I use Python")


只要定义过了一个FirstFunc的函数,输入函数名,即可显示函数所要实现的内容。本函数是打印两行话。

>>> FirstFunc()
First Function!
Life is short,I use Python


可以将这两行话打印若干次,次数自己定。

>>> for i in range(3):
FirstFunc()

First Function!
Life is short,I use Python
First Function!
Life is short,I use Python
First Function!
Life is short,I use Python
>>>


函数的形式十分灵活,可以在函数中间加上关键字,在后面的使用中直接调用,就可以显示不同的名称。

参数从调用的角度,分为形式参数(parameter)实际参数(argument),形参指的是函数创建和定义过程中小括号里的参数,而实参指的是函数在被调用的过程中传递进来的参数。

>>> def SecondFunc(name):
print(name + " is great!")


括号里的是参数,可以改成任何你想要输出的name。

>>> SecondFunc("Python")
Python is great!


SecondFunc(name)中name是形参,因为只代表一个位置,可以表示任何的变量名;而”Python”则是实参,因为它是一个具体的内容,是赋值到变量名中的值!

>>> def Func(name,words):
print(name +'->' +words)


形参的数量可以不止一个,只要在函数中一一对应即可。

>>> Func("Hello","Python")
Hello->Python
>>> Func(words="Python",name="Hello")
Hello->Python


*可以代表全部参数。

>>> def test(*params):
print("有%d个参数"%len(params))
print("第二个参数是:",params[1])


len(params)显示参数长度,Billep被拆分,输出第二个参数 。

>>> test('B','i','l','l','e','p')
有6个参数
第二个参数是: i
>>>


当然,可以同时显示收集参数和位置参数,位置参数默认是最后一位数。

>>> def test(*params,extra):
print("收集参数:",params)
print("位置参数:",extra)


把extra =8去掉也能达到同样效果。

>>> test(1,2,3,4,5,6,7,extra =8)
收集参数: (1, 2, 3, 4, 5, 6, 7)
位置参数: 8


当不写return语句的时候,默认Python会认为函数是return none的。

>>> def hello():
print("Hello world!")
>>> print(hello())
Hello world!
None
>>> def hello():
return("Hello world!")
>>> print(hello())
Hello world!


函数变量的作用域,分为局部变量(Local Variable)和全局变量(Global Variable)。

>>> def discounts(price,rate):
final_price = price*rate
return final_price
>>> old_price = float(input('请输入原价:'))
请输入原价:80
>>> rate = float(input('请输入折扣率:'))
请输入折扣率:0.6
>>> new_price = discounts(old_price,rate)
>>> print('打折后的价格是:',new_price)
打折后的价格是: 48.0
>>>


global关键字,可以在函数中定义全局变量

>>> count =5
>>> def func():
count = 10
print(count)
>>> func()
10
>>> count
5
>>> count =5
>>> def func():
global count
count = 10
print(count)

>>> func()
10
>>> count
10


允许在函数内部创建另一个函数,这种函数称为内嵌函数或者内部函数。

>>> def fun1():
print("fun1()正在被调用")
def fun2():
print("fun2()正在被调用")
fun2()

>>> fun1()
fun1()正在被调用
fun2()正在被调用
>>>


闭包(closure)。如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是一个闭包。

>>> def func(x):
def funy(y):
return x*y
return funy
>>> i=func(5)
>>> i(8)
40


也可以直接这么写。

>>> func(5)(8)
40

>>> def funX():
x = [5]
def funY():
x[0] *=x[0]
return x[0]
return funY
>>> funX()()
25
>>>


nonlocal可以在内部函数中修改外部函数里局部变量的值。

>>> def funX():
x = 5
def funY():
nonlocal x
x *=x
return x
return funY
>>> funX()()
25
>>>


lambda表达式

在我理解,lambda就是随时可定义可用的def,不需要像背一本def的规定,而是一本即用即定义的便利贴

>>> funX()()
25
>>> g = lambda x:2*x+1
>>> g(4)
9
>>> g = lambda x,y:3*x+4*y
>>> g(3,4)
25
>>>


filter()过滤器,保留你关注的信息,丢掉不关注的信息。

>>> temp = filter(None,[1,0,2,False,True])
>>> list(temp)
[1, 2, True]
>>> def odd(x):
return x%2
>>> temp = filter(odd,range(10))
>>> list(temp)
[1, 3, 5, 7, 9]
>>>
>>> list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]


map()类似“映射”,有两个参数,一个是函数,一个是可迭代序列,可以对这个序列进行加工。

>>> list(map(lambda x:x*2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


一个求阶乘的函数:

recursion.py
def recursion(n):
result = n
for i in range(1,n):
result *= i
return result
number = int(input('请输入一个整数:'))
result = recursion(number)
print("%d的阶乘是:%d"%(number,result))
RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python36/recursion.py
请输入一个整数:5
5的阶乘是:120
>>>


递归版本的求阶乘函数:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
number = int(input('请输入一个整数:'))
result = factorial(number)
print("%d的阶乘是:%d"%(number,result))
RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python36/recursion.py
请输入一个整数:5
5的阶乘是:120
>>>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 python 应用 体验