Python基础---函数(所有的函数都是对象)Part1

引入:

我们知道一个数列有以下特征:0,1,2,3,5,8,13,21 ......,那么我们称这种数列为斐波那契数列( Successione di Fibonacci)。

在计算机程序里,当n=8时,我们可以很快的列出来,但是如果n=100呢?

欸~这个时候函数,给我们提供了莫大的帮助。

我们来看看,函数能为我们带来怎么样的变化?

抽象:

我们抽象的概括下它的特征,表示为:F0=0,F1=1,Fn=Fn-1+Fn-2(n=100,n∈N*)。

n = 2, F2 = 0+1 = 1

n=3,F3 = 1+2 = 3

...

F100 = F98 + F99

函数很快速的解决了我们的问题,我们来看看函数和过程有什么差别?

函数抽象了一个方式方法,可以不了解内部的流程来获得自己想要的结果,所以函数和过程是相对的。

 

接下来,我们来看看函数在Python中是如何使用的。

在学习函数是如何使用之前,我们先看下函数有哪些特性和特征。

  • 有无返回值

         有返回值

def hello():
...     return [1,2,3]
>>> hello()
[1, 2, 3]

>>> type(hello())
<class 'list'>
>>>

有返回值时,我们的hello方法的类型是一个list。

         无返回值  

>>> def hello():
...     print([1,2,3])
...
>>> hello()
[1, 2, 3]
>>> type(hello())
[1, 2, 3]
<class 'NoneType'>

无返回值时,该hello函数的类型是none type,说明它的类型是none。

可以看到,根据返回值的有无和不同,我们的函数的类型也是不同的。

  • 全局变量(Global Variable)和局部变量(Local Variable)

局部变量 Local Variable  --- 我的地盘听我的

# coding: utf-8

def test():
    name = 'Tom'
    age = 20
	return "My name is {0}, age is {1}".format(name,age)
print(name)

>>>
   print(name)
NameError: name 'name' is not defined

局部变量name在函数的外部被使用时,会报not defined错误,因为函数内的变量只归于test函数管控,出了门就不知道了。

全局变量 Global Variable

全局变量就比局部变量作用范围大了;我们来看几个场景:

1. 全局变量能在局部范围(比如函数内部)可用

# coding: utf-8

def discount(price,rate):
	final_price = price*rate
	print("old_price", old_price)
	return final_price

old_price = 100
rate = 0.8
new_price = discount(old_price,rate)
print("new_price",new_price)
	


结果:
old_price 100
new_price 80.0

2. 全局变量能否在局部范围内进行修改:

# coding: utf-8

def discount(price,rate):
	final_price = price*rate
    old_price = 50
	print("old_price", old_price)
	return final_price

old_price = 100
rate = 0.8
new_price = discount(old_price,rate)
print("new_price",new_price)
	


结果:
old_price 50
new_price 80.0

虽然你是试图在function内修改全局变量,但是并没达到自己认为的效果,因为python会自动默认为在函数内部建立一个局部变量,只是和全局变量名字一样而已,所以局部变量还是局部变量,你终究还是那个命运啊。

那如果真的想修改全局变量怎么办呢?

我们要用一个关键字 global来操作,看实例:

# coding: utf-8
old_price = 100
rate = 0.8

def discount(price,rate):
	final_price = price*rate
	global old_price
	old_price = 50
	print("Inner old_price", old_price)
	return final_price

new_price = discount(old_price,rate)

print("Out old_price", old_price)

print("new_price",new_price)
	

结果:
Inner old_price 50
Out old_price 50
new_price 80.0

通过添加global关键字,我们给变量打了tag,无论在外部内部,它都是我们认为的那个全局变量,世界由我掌控,我就可以任意更改啦。

但是还是要注意的是,不要随意去修改一个全局变量,这样会让程序的可读性变差,产生错误也难以定位和维护。

  • 闭包

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

太抽象,还是看实例。

def fun1():
	print("调用Fun1")
	def fun2():
		print("调用Fun2")
	fun2()

fun1()


结果:
调用Fun1
调用Fun2

这样是不是明白了些呢?对于fun1内部的fun2来说,我们想在fun1内引用fun2,那么fun2就被认为是闭包;

如果在外部调用fun2(),一定会报错:function is not defined。因为fun1内的地盘就该听他的啊,这点一定要记住哦。

==============================================我是分割线========================================

函数分类:Python自己的内置函数和自定义的函数;

1. 内置函数: build in functions

在命令行输入 dir(__builtins__) 来获得整个Python提供给我们多少内置方法。

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

算一算是len(dir__builtins__) =  153个内置函数。

如果要熟悉这些内置函数的话,biubiubiu,木有实例!给你传送门:http://www.runoob.com/python/python-built-in-functions.html 

感兴趣的话,可以看下两个比较特别的内置函数 filter() 和map()。

2. 匿名函数:

  • lambda表达式

如果一个函数是

def ds(x):
    return 2*x +1
>>>ds(5)
>> 11

那么使用lambda的话

格式:lambda 变量 :表达式

lambda x: x*2+1

看,一个简单的、简短的无需命名的表达式,就能省下定义函数的过程。

配合filter() 和 map() 使用会更棒哦!

 

========================================分割线================================================

函数的用法极其灵活和广泛,下面盗用,噢不,粘贴下小甲鱼的基础习题给大家练练手,走过路过,不要忘记点个赞那!

习题:

欢迎大家楼下讨论,下一篇,我们更加深入的看Python中,函数的种类和用法。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值