Boolean
True 1
False 0
Boolean可以被當做數字進行加減
>>> True + True
2
>>> True - False
1
>>> True * False
0
>>> True / False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: int division or modulo by zero
也可以用Boolean表達式
>>> size = 1
>>> size < 0
False
>>> size = 0
>>> size < 0
False
>>> size = -1
>>> size < 0
True
Number
Python支援integer和float,區分他們隻是數字中是否包含小數點
>>> type(1) ①
<class 'int'>
>>> isinstance(1, int) ②
True
>>> 1 + 1 ③
2
>>> 1 + 1.0 ④
2.0
>>> type(2.0)
<class 'float'>
1、使用type()方法檢查類型,傳回int
2、使用isinstance()方法傳回True
3、整數相加還是整數
4、int和float相加自動轉換為float
int和float轉換
>>> float(2) ①
2.0
>>> int(2.0) ②
2
>>> int(2.5) ③
2
>>> int(-2.5) ④
-2
>>> 1.12345678901234567890 ⑤
1.1234567890123457
>>> type(1000000000000000) ⑥
<class 'int'>
1、使用float()方法将int轉換為float
2、使用int()方法将float轉換為float()
3、int()方法将數字截斷,而非四舍五入
4、int()方法将負數向0截斷,不帶四舍五入
5、float類型隻能到小數點後15位
6、int類型可以無限大
(Python3中取消了Python2中的long類型,是以現在的int相當于long)
支援的數字運算
>>> 11 / 2 ①
5.5
>>> 11 // 2 ②
5
>>> .11 // 2 ③
.6
>>> 11.0 // 2 ④
5.0
>>> 11 ** 2 ⑤
121
>>> 11 % 2 ⑥
1
1、/除法預設傳回float類型,即使是兩個整數也傳回float
2、3、/./除法傳回正數向上入負數向下取的,都是整數時傳回int
4、其中一個數為float時,傳回float
5、**表示取11的2次方
6、%表示取餘
Fraction使用分數
>>> import fractions ①
>>> x = fractions.Fraction(1, 3) ②
>>> x
Fraction(1, 3)
>>> x * 2 ③
Fraction(2, 3)
>>> fractions.Fraction(6, 4) ④
Fraction(3, 2)
>>> fractions.Fraction(0, 0) ⑤
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "fractions.py", line 96, in __new__
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
ZeroDivisionError: Fraction(0, 0)
1、要使用分數,使用import指令導入fractions module
2、定義一個分數,建立Fraction對象并傳遞分子和分母
3、使用數字操作符對分數進行計算,傳回新的Fraction對象
4、Fraction對象會自動進行分子分母的xxx忘了叫啥了(6/4) = (3/2)
5、不能用0做分母,會抛異常
TRIGONOMETRY使用三角函數
>>> import math
>>> math.pi ①
3.1415926535897931
>>> math.sin(math.pi / 2) ②
1.0
>>> math.tan(math.pi / 4) ③
0.99999999999999989
1、math module中有pi的常量
2、math module中有常用的三角函數方法sin(),cos().tan()和其他的反正弦反餘弦asin(),acos()等
3、tan(π / 4) should return 1.0, python支援的精度有限
數字在boolean表達式中
0為false,非0數值為true