0.6 四则运算+余数+四舍五入
1.数据类型
整型(int)
浮点型(float)
字符型(str)
#下面先声明 变量,并赋值 a = 5 # a 是 整型(int) : 数学里的 整数 b = 5.0 # b 是 浮点型(float) :数学里的 小数 c = ' heloo , world ' # c 字符串类型(str)
2. 加(+),减(-),乘(*),除(/)
看下述代码
>>>6 + 2 8 >>>6 - 2 4 >>>6 * 2 12 >>>6/2 3.0 #
和我们小学学习的一样,因为计算机语言是人类创造的所以人的掌握的知识会应用到计算机语言内,这点就不多说了
为什么 6 / 2 = 3.0 呢
答:因为这是python规定
在python里,如果没有强制类型转换的话,不管是 整型 / 浮点型 , 浮点型 / 整型 , 还是 整型 / 整型 ,结果都是 浮点型
3. 余数
在Python,用 % 符号 来取得两个数相除的余数。
1. 怎么知道一个数的和别一个数相乘之后的 商 和 余数 ?
利用divmod函数可以直接获得 商 和 余数 , 如下图
>>> divmod(5,2) #divmod( 被除数 , 除数)
(2,1) #(商 , 余数)
在Python里,如果没有强制类型转换的话,整型 % 浮点型 , 浮点型 % 整型 为浮点型 , 只有 整型 % 整型 为 整型 , 如下图实列
>>> 5.0 % 2 1.0 >>> 5 % 2.0 1 >>> 5 % 2 1
4. 四舍五入
在Python用 round() 函数来表示将一个数四舍五入
>>> round(5.25.5 , 2) #round(需要四舍五入的数 ,舍去的数的小数点后的第几个数后面的数 ) 5.06 >>> round(5.25.4 , 2) 5.25 >>> round(5.54321 , 5) 5.54321 #下述代码是别人发现 >>> round(2.235,2) 2.23 #应该是:2.24 浮点数中的十进制转化为二进制惹的祸
5.divmod 和 id 函数
使用方法
>>> divmod (10 , 4) # (前被除数 , 后者 除数) (2, 2) >>> temp = divmod (9 , 4 ) >>> print (temp) >>> (2, 1) >>> id (temp) #用内建函数id()可以查看每个对象的内存地址,即身份
49091080 >>> type (temp) <class 'tuple'>
6. 整数溢出问题
>>> 3 ** 1000 # ** 表示多少次方 132207081948080663689045525975214436596542203275214816766492036822682859734670489954
077831385060806196390977769687258235595095458210061891186534272525795367402762022519
832080387801477422896484127439040011758861804112894781562309443806156617305408667449
050617812548034440554705439703889581746536825491613622083026856377858229022841639830
788789691855640408489893760937324217184635993869551676501894058810906042608967143886
102814350385648747165832010614366132173102768902855220001 >>> # 由于上数过大 超过了int的 范围 所以 程序会转换为 long
7. import math 计算o(╥﹏╥)o库 dir () help ()
>>> import math
>>> math.pi #计算圆周率
3.141592653589793
>>> dir(math) =
['__doc__', '__nme__', '__package__', 'acos', 'acosh',
>>> help (math) #查看使用方法
Help on built-in module math:
NAME
math
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
>>> math . pow(4 ,2) #相当于4 ** 2
16.0

浙公网安备 33010602011771号