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等,分別表示被轉換的數為十六進位形式、八進位形式和二進位形式。