Python 函式和模組

pursuer.chen發表於2016-06-29

介紹

在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

本站點所有隨筆都是原創,歡迎大家轉載;但轉載時必須註明文章來源,且在文章開頭明顯處給明連結。

《歡迎交流討論》

相關文章