第二章Python的Boolean,Number,运算符,Fraction分数,TRIGONOMETRY三角函数

来源:互联网 发布:cookie json 编辑:程序博客网 时间:2024/06/05 10:08

Boolean

True   1

False 0

Boolean可以被当做数字进行加减

>>> True + True2>>> True - False1>>> True * False0>>> True / FalseTraceback (most recent call last):File "<stdin>", line 1, in <module>ZeroDivisionError: int division or modulo by zero
也可以用Boolean表达式
>>> size = 1>>> size < 0False>>> size = 0>>> size < 0False>>> size = -1>>> size < 0True

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) ②>>> xFraction(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