1. 程式人生 > >python 資料型別和四則運算

python 資料型別和四則運算

不懂的時候就google. ### 按照下面要求,在ide中執行:

>>> 2+5
7
>>> 5-2
3
>>> 10/2
5
>>> 5*2
10
>>> 10/5+1
3
>>> 2*3-4
2

繼續要在ide中運算一下:

>>> 4+2
6
>>> 4.0+2
6.0
>>> 4.0+2.0
6.0

以上就:引入兩個資料型別:整數和浮點數

大數相乘

>>> 123456789870987654321122343445567678890098876*1233455667789990099876543332387665443345566
152278477193527562870044352587576277277562328362032444339019158937017801601677976183816L 

上面計算結果的數字最後有一個L,就表示這個數是一個長整數

  • 整數,用int表示,來自單詞:integer
  • 浮點數,用float表示,就是單詞:float 可以用一個命令:type(object)來檢測一個數是什麼型別。
>>> type(4)
<type 'int'>    #4是int,整數
>>> type(5.0)
<type 'float'> #5.0是float,浮點數
type(988776544222112233445566778899887766554433221133344455566677788998776543222344556678)
<type 'long'>   #是長整數,也是一個整數

幾個常見函式

求絕對值

>>> abs(10)
10
>>> abs(-10)
10
>>> abs(-1.2)
1.2

四捨五入

>>> round(1.234)
1.0
>>> round(1.234,2)
1.23

>>> #如果不清楚這個函式的用法,可以使用下面方法看幫助資訊
>>> help(round)

Help on built-in function round in module __builtin__:

round(...)
    round(number[, ndigits]) -> floating point number

    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.

冪函式

>>> pow(2,3)        #2的3次方
8

math模組(對於模組可能還有點陌生,不過不要緊,先按照下面程式碼實驗一下,慢慢就理解了)

>>> import math         #引入math模組
>>> math.floor(32.8)    #取整,不是四捨五入
32.0
>>> math.sqrt(4)        #開平方
2.0