python笔记:定义函数


1、自定义函数存放在外部文件中的调用方式
2、空函数
3、参数检查
4、返回值
1、自定义函数存放在外部文件中的调用方式

如果将函数myabs()定义在外部文件abstest.py中,在该文件的当前目录下启动python解释器,用from abstest import my_abs,就可以使用该函数了

2、空函数

表示该函数什么也不做

def myabs1():

    pass

3、参数检查

(1)情况一、参数个数不对:

python解释器对于内置函数和自定义函数都会自动检查出来,并抛出typeError,比如:

 my_abs() takes 1 positional argument but 2 were given

(2)情况二、参数类型不对:

python解释器对于内置函数会检查出参数错误,并抛出

TypeError: bad operand type for abs(): 'str'

python解释器对于自定义函数检查不出来参数错误,会导致if语句错误,说明函数定义的不够完善

  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in my_abs
TypeError: unorderable types: str() >= int()

改善:函数中第一句语句位置加上

 if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')

4、返回值

(1)可以返回多个值

示例:已知初始坐标,移动位移,移动角度,返回移动后的坐标

import math

def move(x, y, step, angle=0):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny

(2)也可以无返回值

return等价于 return none




注:总结自廖雪峰python教程

猜你喜欢

转载自blog.csdn.net/zyckhuntoria/article/details/80600418