python学习笔记(十二)之函数

牛刀小试:

  定义一个无参函数

1 >>> def myFirstFunc():
2 ...     print("Hello python")
3 ...     print("hello world")
4 ...     print("hello my fist func")
5 ... 
6 >>> myFirstFunc()
7 Hello python
8 hello world
9 hello my fist func
View Code

  定义一个有参函数

1 >>> def mySecondFunc(name):
2 ...     print("hello", name)
3 ... 
4 >>> mySecondFunc('zhz')
5 hello zhz
View Code

函数之形参和实参

1 >>> def add(first, second):
2 ...     return first + second
3 ... 
4 >>> add(1, 5)
5 6
View Code

定义函数时,first和second就是形参,在函数调用时,传递的1和5就是实参。

函数之注释和文档

1 >>> def add(first,second):
2 ...     '这是函数文档:计算两个参数的和'
3 ...     #这是函数注释:计算两个参数的和
4 ...     return first + second
5 ... 
View Code

函数文档可以使用以下方式查看

1 >>> add.__doc__
2 '这是函数文档:计算两个参数的和'
3 
4 >>> help(add)
5 
6 Help on function add in module __main__:
7 
8 add(first, second)
9     这是函数文档:计算两个参数的和
View Code

 函数之关键字参数

1 >>> def saysome(name, words):
2 ...     print(name, '->', words)
3 ... 
4 >>> saysome('Jobs', 'stay hungry,stay foolish')
5 Jobs -> stay hungry,stay foolish
6 >>> saysome('stay hungry,stay foolish','Jobs')
7 stay hungry,stay foolish -> Jobs
8 >>> saysome(words = 'stay hungry,stay foolish',name = 'Jobs')
9 Jobs -> stay hungry,stay foolish
View Code

函数之默认参数

 1 >>> def saysome(name = 'Jobs', words = 'stay hungry, stay foolish'):
 2 ...     print(name, '->', words)
 3 ... 
 4 >>> saysome()
 5 Jobs -> stay hungry, stay foolish
 6 >>> saysome('nazi')
 7 nazi -> stay hungry, stay foolish
 8 >>> saysome(words = 'keep working')
 9 Jobs -> keep working
10 >>> saysome('nazi','keep looking')
11 nazi -> keep looking
View Code

函数之收集参数

1 >>> def test(*params):
2 ...     for i in range(len(params)):
3 ...             print(params[i])
4 ... 
5 >>> test(1, 'hello', (1,3, ['abc']))
6 1
7 hello
8 (1, 3, ['abc'])
View Code

收集参数后最好使用默认参数,用关键字参数调用。

函数返回值

  python中,用return语句可以从函数返回一个对象,列表或元组。当没有显示调用return语句时,python会自动返回一个NoneType对象。所以,可以说python中只有函数,没有过程。

 1 >>> def hello():
 2 ...     print("Hello")
 3 ... 
 4 >>> temp = hello()
 5 Hello
 6 >>> print(temp)
 7 None
 8 >>> type(temp)
 9 <class 'NoneType'>
10 >>> def back():
11 ...     return 1,2,'abc',[1,2]
12 ... 
13 >>> back()
14 (1, 2, 'abc', [1, 2])
15 >>> def back():
16 ...     return [1, 3.14, 'abv', [2]]
17 ... 
18 >>> back()
19 [1, 3.14, 'abv', [2]]
View Code

局部变量和全局变量

  在函数内部声明的变量是局部变量,在函数外声明的变量是全局变量。

 1 def discount(price,rate):
 2     'final_price, price, rate are local variables'
 3     final_price = price * rate
 4     return final_price
 5     
 6 if __name__ == '__main__':
 7     'old_price, rate and new_price are global variables'
 8     old_price = float(input("原价:"))
 9     rate = float(input("折扣:"))
10     new_price = discount(old_price, rate)
11     print("折后价:", new_price)
View Code

  在函数中试图修改一个全局变量的值时,会python创建一个和全局变量相同的局部变量,此时,修改的只是该局部变量,全局变量不变。

1 >>> number = 10
2 >>> def test():
3 ...     number = 5
4 ...     
5 ... 
6 >>> test()
7 >>> number
8 10
View Code

  要在函数内部修改全局变量的值,可以使用global关键字。

1 >>> number
2 10
3 >>> def test():
4 ...     global number
5 ...     number = 5
6 ... 
7 >>> test()
8 >>> number
9 5
View Code

内嵌函数

  在函数内部可以定义其他函数,这个内部函数的作用域仅限于外部函数内部。在外部函数外部的任何位置使用该内部函数,都会抛出一个异常。

 1 >>> def funA():
 2 ...     print("funA")
 3 ...     def funB():
 4 ...             print("funB")
 5 ...     funB()
 6 ... 
 7 >>> funA()
 8 funA
 9 funB
10 >>> funB()
11 Traceback (most recent call last):
12   File "<stdin>", line 1, in <module>
13 NameError: name 'funB' is not defined
View Code

闭包

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

 1 >>> def funX(x):
 2 ...     def funY(y):
 3 ...             return x*y
 4 ...     return funY
 5 ... 
 6 >>> i = funX(5)
 7 >>> type(i)
 8 <class 'function'>
 9 >>> i(6)
10 30
11 >>> funX(5)(6)
12 30
View Code

  同样的,在闭包内修改外部作用域变量,系统会自动创建局部变量x,屏蔽外部变量。

 1 >>> def fun1():
 2 ...     x = 5
 3 ...     def fun2():
 4 ...             x *= x
 5 ...     fun2()
 6 ... 
 7 >>> fun1()
 8 Traceback (most recent call last):
 9   File "<stdin>", line 1, in <module>
10   File "<stdin>", line 5, in fun1
11   File "<stdin>", line 4, in fun2
12 UnboundLocalError: local variable 'x' referenced before assignment
View Code

  此时要修改外部变量,一,可以使用列表,列表不是放在栈里。

1 >>> def fun1():
2 ...     x = [5]
3 ...     def fun2():
4 ...             x[0] *= x[0]
5 ...     fun2()
6 ...     print(x)
7 ... 
8 >>> fun1()
9 [25]
View Code

  二,可以使用nolocal关键字

 1 def fun1():
 2     x = 5
 3     def fun2():
 4         nonlocal x
 5         x = 50
 6     fun2()
 7     print(x)
 8 
 9 if __name__ == '__main__':
10     fun1()
View Code

 

posted @ 2017-10-31 20:28  去伪存真  阅读(259)  评论(0编辑  收藏  举报