Python 函数和模块

介绍

在python中也存在函数的概念,标准的函数我们可以叫内置函数,这类函数可以直接通过函数名进行调用。但是还有其它的一些不是内置的函数就不能直接通过函数名进行调用了,比如floor函数(向下取整),这时我们就需要用到模块;本篇主要介绍math和cmath。

python版本:3.4.4

内置函数(标准函数)

先来看一下标准函数,如果使用IDLE程序做测试,输入内置函数时函数名称的颜色会变成紫色,而非内置函数则不会。

1.abs:绝对值

>>> abs(-5)
5

2.pow(x,y):x的y次方

>>> pow(2,3)
8

非内置函数

语法

import math[cmath]

math[cmath].function_name

from math[cmath] improt function_name

注意:cmath的用法和math是一样,但是cmath是用来处理复数,比如你需要对一个负数进行求平方根时,这时就需要用到cmath 

1.floor:向下取整

>>> floor(31.5)
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    floor(31.5)
NameError: name 'floor' is not defined

由于floor不是标准函数,直接调用会报错,这时就需要用到模块。

>>> import math
>>> math.floor(31.5)
31
>>> from math import floor
>>> floor(31.5)
31

2.sqrt:取平方根

>>> import math
>>> math.sqrt(4)
2.0
>>> math.sqrt(-4)
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    math.sqrt(-4)
ValueError: math domain error

可以看到使用math对负数进行取平方根会报错,这时就需要使用cmath

>>> import cmath
>>> cmath.sqrt(-4)
2j
>>> from cmath import sqrt
>>> sqrt(-4)
2j

其它函数

 

总结

 python的语法在每个新的版本会存在变化,需要经常关注每个新版本有哪些改动的地方。

备注:

    作者:pursuer.chen

    博客:http://www.cnblogs.com/chenmh

本站点所有随笔都是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。

《欢迎交流讨论》

原文地址:https://www.cnblogs.com/chenmh/p/5593924.html