Python學習-資料運算,python學習運算

來源:互聯網
上載者:User

Python學習-資料運算,python學習運算

在Python中有豐富的算術運算,這使得Python在科學計算領域有著很高的地位,Python可以提供包括四則運算在內的各種算術運算。

 1 a = 10 2 b = 20 3 print(a+b)       #30 4 print(a-b)       #-10 5 print(a*b)       #200 6 print(a*b)       #200 7 print(a/b)       #0.5 8 print(a%b)       #10,返回餘數 9 print(a**b)       #10^2010 print(a//b)       #0,取整,返回商的整數部分11 12 print(a and b)    #與操作,傳回值為2013 print(a or b)    #或操作,傳回值為1014 print(not(a and b))    #非操作,傳回值為false

三元運算:

結果 = 值1  if 條件 else 值2

結果的取值由條件進行控制,如果條件為真,即成立,值1的賦值給結果,如果條件為假,即不成立,值2的賦值給結果。

1 #三元運算:結果 = 值1 if 條件 else 值22 a,b,c = 1,3,53 d = a if a > b else c4 print(d)     #5

 進位轉換:

表示各進位的符號: b:二進位,o:八進位,d:十進位,x:十六進位 bin()、oct()、hex()傳回值均為字串,且分別帶有0b、0o、0x首碼。 
hex函數比格式化字串函數format慢,不推薦使用。 eval函數比int函數慢,不推薦使用。二進位、十六進位、八進位之間的轉換,可以藉助十進位這個中間值,即先轉十進位再轉其他進位,也可以直接使用函數進行轉換。
 1 #進位轉換 2 print(bin(10))      #十進位轉二進位:0b1010,其中0b表示二進位 3 print('{0:b}'.format(10))    #1010 4  5 print(oct(12))      #十進位轉八進位:0o14,其中0o表示八進位 6 print('{0:o}'.format(12))     #14 7  8 print(hex(12))      #十進位轉十六進位:0xc,其中0x表示十六進位 9 print('{0:x}'.format(12))     #c10 11 print(int('1010',2))  #二進位轉十進位:10,其中int中的兩個參數分別為要轉換的數和該數的進位12 print(eval('0b1010'))   #1013 14 print(int('014',8))   #八進位轉十進位:1215 print('{0:d}'.format(0o14))     #12,需要強調14為八進位的14,所以應該表示成0o1416 17 print(int('0xc',16))    #十六進位轉十進位:1218 print(eval('0xc'))     #12

在使用format格式化輸出進行進位轉換時,例如:'{0:d}'.format(0o14),其中'd'代表目標進位符號,也就是需要轉換成的進位,format括弧內部,當被轉換數不為十進位數時,需要在被轉換數前面加上進位符號,如0x,0o,0b等,分別表示被轉換的數為十六進位形式、八進位形式和二進位形式。

 

  

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.