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