python-函数

abs()  求绝对值

max()  求最大值

python内置的常用函数还包括数据类型转换函数,如int() 函数可以把其他数据类型转换为整数

hex() 函数把一个整数转换成十六进制表示的字符串

 

定义函数

python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:, 然后在缩进块中编写函数体,函数的返回值用return语句返回。

例:

def my_abs (x):

  if x >= 0:

    return x

  else:

    return -x

 空函数:

def nop ():

  pass

pass语句什么都不做,它可以用来作为占位符。现在还没想好怎么写函数的代码,就可以先放一个pass,不会报错。  在if语句里也可以用。

数据类型检查可以用isinstance()

 

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

 

返回多个值

函数可以返回多个值

import math

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

impot math 语句表示导入math包,并且允许后续代码引用math包里的sin、 cos等函数。

 

posted @ 2018-05-15 15:33  aplious  阅读(114)  评论(0编辑  收藏  举报