Python 学习笔记03【函数】
3.1 函数语句和参数
def 函数名(参数):
函数体
注:函数调用完成之后,参数变量就被销毁。
3.2 返回值和return语句
3.3 None值
None是NoneType类型的唯一值。
在幕后,对于没有return语句的函数,Python会在函数末尾上加上return None(类似于,for循环和while循环末尾隐式地加上continue)
3.4 关键字参数和print()
关键字参数,由 关键字 和 参数 共同组成的。
print('Hello Word') ,背后是 print('Hello Word', end='\n', sep='')
打印多个字符串,默认通过空格分割,可以修改sep关键字来自定义,如下:

3.5 局部和全局作用域
- 在被调用函数内赋值和变元和变量,处于该函数的“局部作用域”---“局部变量”
- 在所有函数之外赋值的变量,属于“全局作用域”---“全局变量”
“作用域”可以看做是变量的容器,作用域销毁,对应的变量也被销毁。
3.5.1 局部变量不能在全局作用域内使用
3.5.2 局部作用于不能使用其他局部作用域的变量
3.5.3 全局变量可以在局部作用域中读取
3.5.4 局部变量和全局变量的名称可相同
3.6 global语句:在局部作用域中修改全局变量
辨别局部变量和全局变量的4条法则:
- 如果变量在全局作用域中使用(在所有函数之外),即为全局变量
- 如果在函数中,有针对该变量的global语句,即为全局变量
- 如果变量用于函数中的赋值语句,即为局部变量
- 如果变量在函数内,但是没有被赋值而直接使用,即为全局变量
def spam(): golbal eggs#法则2 eggs = 'spam' def bacon(): eggs = 'bacon' #法则3 def ham(): print('eggs') #法则4 eggs = '42' # 法则1 注:一个函数内部,不能有局部变量和全局变量重名
3.7 异常处理
Python程序中的错误或异常,会导致整个程序崩溃。我们希望异常被检测和捕捉,处理之后,保证程序继续运行。
可以使用try-except 语句处理异常
1 def spam(dividedBy): 2 try: 3 return 42/dividedBy 4 except ZeroDivisionError: 5 print('Error: Invalid argument') 6 7 print(spam(2)) 8 21.0 9 print(spam(0)) 10 Error: Invalid argument 11 None
1 def spam1(dividedBy):
2 return 42/dividedBy:
3
4 try:
5 print(spam1(2))
6 print(spam1(12))
7 print(spam1(0))
8 print(spam1(1))
9 except ZeroDivisionError:
10 print('Error: Invalid argument')
13 21.0
14 3.5
15 Error: Invalid argument
print(spam1(1))没有被执行,是因为执行print(spam1(0))抛异常,直接跳转到 except语句,except语句执行完之后,不会再调回try语句。
3.8 空函数
如果想定义一个什么事也不做的空函数,可以用pass语句:
def nop(): pass
pass可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。
pass还可以用在其他语句里,比如:
if age >= 18: pass
缺少了pass,代码运行就会有语法错误。
3.9 自定义函数的调用
定义函数 my_abs
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def my_abs(x): # 参数类型检查 if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x
将函数的源文件保存为
function_my_abs.py,目录为self_path
在self_path下启动python, 并通过 from_import 导入 my_abs 函数
[@wooluwakerdeMBP:test]$ python
Python 3.7.5 (default, Oct 25 2019, 10:52:18)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from function_my_abs import my_abs
>>> my_abs(99)
99
>>> my_abs(-999)
999
3.10 函数返回多个值
#!/usr/bin/env python # -*- coding:utf-8 -*- def test_return_2(x,y):
# 检查参数类型 if not isinstance(x,int): raise TypeError('x not int type') if not isinstance(y,int): raise TypeError('y not int type') return x*x, y*y
test_return_2(2,3.0) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-cb19da420d18> in <module>() ----> 1 test_return_2(2,3.0) <ipython-input-32-546309225eaa> in test_return_2(x, y) 6 raise TypeError('x not int type') 7 if not isinstance(y,int): ----> 8 raise TypeError('y not int type') 9 return x*x, y*y TypeError: y not int type
# 函数两个返回值组成一个tuple
res = test_return_2(2,3) print(res) print(type(res))

浙公网安备 33010602011771号