时间:2021-08-07 python教程 查看: 1016
我们知道**代表次方。
>>>12 * 12
144
>>>12 ** 2
144
>>>a=1e200
>>> a
1e+200
>>>a ** 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>>a * a
inf
>>>a = 100 ** 100 # python3中int整型一般不会溢出,取决于内存
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>>a * a,a ** 2 # 两种方式都没问题,int很大,不会溢出,取决于内存
(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
>>>float(a) * float(a) #float用这种方法,也不会溢出
inf
>>>float(a) ** 2 #float用这种方式有可能溢出,注意!!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
补充:python3.8中运算符/和//区别
5/5的结果为1.0,5//5的结果为1
6.0/5.0的结果为1.2,6.0//5.0的结果为1.0
由此可见,使用/运算符时,即使两参数都是int,返回值都是float,而运算符//只有当参数中含有float时,返回值是float,但是结果是取整的。
//运算符的结果是最小取整的,/运算符会保留小数位
补充:python3中运算符及其优先级
+ - * /(真除法) % //(地板除-floor) **(幂运算)
=
+= -= *= /= %= **= //=
a+=1 (运行效率高)
a=a+1 (运行效率低)
== > < >= <= !=
可以连续判断:
3>2>1
True
3>2 and 2>1
True
not and or 优先级:
not优先级最高
and
or 优先级最低
位:二进制下的每一个位
<< >> :移位运算符
&:逻辑求与
|:逻辑求或
~:逻辑求非
^:逻辑求异或
变量=(值1 if 布尔表达式 else 值2)
如果布尔表达式位真则返回值1否则返回值2
运算符中,三元运算符的优先级最低
1. 先乘除后加减
2. 幂运算优先级最高
3. 三元运算符优先级最低
4. 元数越少,优先级越高
幂运算:一元运算符
5. 优先级从高到低排列:
幂运算
正负号
算数运算符(— = * /)
比较运算符(< > <= >=)
逻辑运算符(not and or)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持python博客。