python判斷整數(shù)的方法:1、可以使用字符串str的is digit方法判斷字符串是否是一個(gè)僅有數(shù)字組成;2、可以使用【try-except】語句捕獲ValueError,并繼續(xù)請求輸入。

本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,DELL G3電腦。
python判斷整數(shù)的方法:
1、可以使用字符串str的is digit方法判斷字符串是否是一個(gè)僅有數(shù)字組成,也就是整數(shù)。如果是整數(shù)退出while循環(huán),否則繼續(xù)請求輸入。
while True: x = input('Input an integer: ') if x.isdigit(): break else: print 'Please input an *integer*'
2、也可以使用try-except語句。如果輸入的字符串是整數(shù),那么它可以用用int()函數(shù),轉(zhuǎn)換為int類并退出循環(huán),否則會(huì)出現(xiàn)ValueError,可以使用try-except語句捕獲ValueError,然后繼續(xù)請求輸入。
while True: try: x = input('Input an integer: ') x = int(x) break except ValueError: print 'Please input an *integer*'
相關(guān)免費(fèi)學(xué)習(xí)推薦:python視頻教程
站長資訊網(wǎng)