在數(shù)學(xué)中我們知道一個(gè)數(shù)連續(xù)乘另一個(gè)數(shù),這種操作叫做乘方,乘方的運(yùn)算結(jié)果叫冪,所以乘方運(yùn)算也可以叫求冪,那么python乘方運(yùn)算是怎么表達(dá)的呢?今天小編就帶來一篇python運(yùn)算符詳解,希望能給各位小伙伴帶來一點(diǎn)幫助。
我們知道**代表次方。
如下
>>>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整型一般不會(huì)溢出,取決于內(nèi)存
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>>a * a,a ** 2 # 兩種方式都沒問題,int很大,不會(huì)溢出,取決于內(nèi)存
(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
>>>float(a) * float(a) #float用這種方法,也不會(huì)溢出
inf
>>>float(a) ** 2 #float用這種方式有可能溢出,注意?。?!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
補(bǔ)充:python3.8中運(yùn)算符/和//區(qū)別
看下面這兩張圖:
5/5的結(jié)果為1.0,5//5的結(jié)果為1
6.0/5.0的結(jié)果為1.2,6.0//5.0的結(jié)果為1.0
由此可見,使用/運(yùn)算符時(shí),即使兩參數(shù)都是int,返回值都是float,而運(yùn)算符//只有當(dāng)參數(shù)中含有float時(shí),返回值是float,但是結(jié)果是取整的。
/和//的主要區(qū)別:
//運(yùn)算符的結(jié)果是最小取整的,/運(yùn)算符會(huì)保留小數(shù)位
補(bǔ)充:python3中運(yùn)算符及其優(yōu)先級(jí)
1. 一般運(yùn)算符:
+ - * /(真除法) % //(地板除-floor) **(冪運(yùn)算)
2. 賦值運(yùn)算符:
=
3. 增強(qiáng)運(yùn)算符(增強(qiáng)賦值運(yùn)算符)
+= -= *= /= %= **= //=
a+=1 (運(yùn)行效率高)
a=a+1 (運(yùn)行效率低)
4. 布爾運(yùn)算符(比較運(yùn)算符)
== > < >= <= !=
可以連續(xù)判斷:
3>2>1
True
3>2 and 2>1
True
5. 邏輯運(yùn)算符
not and or 優(yōu)先級(jí):
not優(yōu)先級(jí)最高
and
or 優(yōu)先級(jí)最低
6. 位運(yùn)算符
位:二進(jìn)制下的每一個(gè)位
<< >> :移位運(yùn)算符
&:邏輯求與
|:邏輯求或
~:邏輯求非
^:邏輯求異或
7. 三元運(yùn)算符
變量=(值1 if 布爾表達(dá)式 else 值2)
如果布爾表達(dá)式位真則返回值1否則返回值2
運(yùn)算符中,三元運(yùn)算符的優(yōu)先級(jí)最低
1. 先乘除后加減
2. 冪運(yùn)算優(yōu)先級(jí)最高
3. 三元運(yùn)算符優(yōu)先級(jí)最低
4. 元數(shù)越少,優(yōu)先級(jí)越高
冪運(yùn)算:一元運(yùn)算符
5. 優(yōu)先級(jí)從高到低排列:
冪運(yùn)算
正負(fù)號(hào)
算數(shù)運(yùn)算符(— = * /)
比較運(yùn)算符(< > <= >=)
邏輯運(yùn)算符(not and or)
以上就是python運(yùn)算符詳解的全部?jī)?nèi)容,希望能給大家一個(gè)參考,也希望大家多多支持W3Cschool。