打印數據類型:type
>> > a= 1
>> > print ( type ( a) )
< class 'int' >
int():將一個數值或字符串轉換成整數,可以指定進制。
float():將一個字符串轉換成浮點數。
str():將指定的對象轉換成字符串形式,可以指定編碼。
chr():將整數轉換成該編碼對應的字符串(一個字符)。
ord():將字符串(一個字符)轉換成對應的編碼(整數)。
整除
自然除法/:能整除則整除,不能整除以浮點數的方式返回結果
地板除法//:對不能整除的向下取整
取整函數int:對於整數直接返回原值,對於浮點數返回其整數部分
四捨五入取偶函數round():對於整數直接返回原值,對於浮點數,進行四捨五入,並且向偶數取整。另外both round(0.5) and round(-0.5) are 0, and round(1.5) is 2
向下取整floor():見名知意,當結果在這些區間時(-1,1)取0;(1,2)取1;(n,n+1)取n;(-n,-n-1)n>0取-n-1
向上取整ceil():用法與floor相反,並且都需要導入math模塊
>> > 1 / 2
>> > 1 / 3
>> > 1 // 2
>> > 1 // 3
>> > 7 // 2
>> > - 7 // 2
>> > - ( 7 // 2 )
>> > int ( 1.9999 )
>> > int ( 1.0 )
>> > round ( 1.5 )
>> > round ( - 1.5 )
>> > round ( 0.5 )
>> > round ( 0.500001 )
import math
math. floor( 1.9999 )
math. floor( 1.0 )
math. floor( - 3.4 )
math. ceil( 2.1 )
math. ceil( - 2.999 )
常用的數值處理函數
min ( ) : 對象可以是可迭代對象或者是一列對象
max ( ) :
pow ( x, y) : 冪運算,x** y(x的y次方)
math. sqrt( x) : 開方運算x** 0.5
bin ( ) : 將十進制整型數值轉換位二進制, 返回字符串,類似於'0b1010'
oct ( ) : 將十進制整型數值轉換爲八進制,返回字符串,類似於'0o12'
hex ( ) : 將十進制整型數值轉換爲十六進制,返回字符串,類似於'0xa'
math. pi: 引用π的值
math. e: 引用e的值
另外還有對數函數和三角函數等
類型轉換
a= int ( input ( 'a= ' ) )
b= int ( input ( 'b= ' ) )
print ( '%d + %d = %d' % ( a, b, a+ b) )
賦值運算與複合賦值運算
a = 10
b = 3
a += b
a *= a + 2
print ( a)
比較運算符與邏輯運算
flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
flag3 = flag1 and flag2
flag4 = flag1 or flag2
flag5 = not ( 1 != 2 )
print ( 'flag0 =' , flag0)
print ( 'flag1 =' , flag1)
print ( 'flag2 =' , flag2)
print ( 'flag3 =' , flag3)
print ( 'flag4 =' , flag4)
print ( 'flag5 =' , flag5)
print ( flag1 is True )
print ( flag2 is not False )
將華氏溫度轉換爲攝氏溫度
F= float ( input ( '請輸入華氏溫度:' ) )
f= ( F - 32 ) / 1.8
print ( '攝氏溫度爲:%.3f' % ( f) )
計算圓的面積和周長
import math
r= float ( input ( '請輸入圓的半徑:' ) )
S= math. pi* r** 2
L= 2 * math. pi* r
print ( '圓的面積爲:%.3f' % S)
print ( '圓的周長爲:%.3f' % L)
計算年份
year= float ( input ( '請輸入年份:' ) )
if ( year % 4 == 0 and year % 100 != 0 ) or year % 400 == 0 :
print ( '%d is a special Year' % year)
else :
print ( '%d is not a special Year' % year)