Python函數(shù)中三大主要應(yīng)用形式
Python函數(shù)在使用的時候有幾大分類,其中以int函數(shù),float函數(shù)和str函數(shù)的應(yīng)用最為廣泛。下面我們就看看具體的環(huán)境中如何進行相關(guān)的函數(shù)代碼的編寫。下面我們先來看看int函數(shù)在Python函數(shù)中的作用。
(1)把符合數(shù)學(xué)格式的數(shù)字型字符串轉(zhuǎn)換成整數(shù)
(2)把浮點數(shù)轉(zhuǎn)換成整數(shù),但是只是簡單的取整,而非四舍五入。
舉例:
- aa = int("124") #Correct
 - print "aa = ", aa #result=124
 - bb = int(123.45) #correct
 - print "bb = ", bb #result=123
 - cc = int("-123.45") #Error,Can't Convert to int
 - print "cc = ",cc
 - dd = int("34a") #Error,Can't Convert to int
 - print "dd = ",dd
 - ee = int("12.3") #Error,Can't Convert to int
 - print ee
 
float函數(shù)將整數(shù)和字符串轉(zhuǎn)換成浮點數(shù)。
舉例:
- aa = float("124") #Correct
 - print "aa = ", aa #result = 124.0
 - bb = float("123.45") #Correct
 - print "bb = ", bb #result = 123.45
 - cc = float(-123.6) #Correct
 - print "cc = ",cc #result = -123.6
 - dd = float("-123.34") #Correct
 - print "dd = ",dd #result = -123.34
 - ee = float('123v') #Error,Can't Convert to float
 - print ee
 
Python str函數(shù)將數(shù)字轉(zhuǎn)換成字符舉例:
- aa = str(123.4) #Correct
 - print aa #result = '123.4'
 - bb = str(-124.a) #SyntaxError: invalid syntax
 - print bb
 - cc = str("-123.45") #correct
 - print cc #result = '-123.45'
 - dd = str('ddd') #correct
 - print dd #result = ddd
 - ee = str(-124.3) #correct
 - print ee #result = -124.3
 
以上就是對Python函數(shù)的三大類進行的分析,希望大家有所收獲。
【編輯推薦】















 
 
 

 
 
 
 