日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python怎樣判斷一個數值(字符串)為整數_python

作者:mz_老張 ? 更新時間: 2023-05-29 編程語言

如何判斷一個數值(字符串)為整數

不嚴格檢查方法

浮點數的自帶方法is_integer()

如果確定輸入的內容為浮點數,是可以直接使用float數的is_integer()函數來進行判定。

需要注意的是當數字是 1.0這樣的不帶小數數值的浮點數時,會被默認判定為整數

a=1.0
print(a.is_integer())
#結果為
True

b=1.1
print(b.is_integer())
#結果為
False

但是如果數字本身就是int類型,那么沒有is_integer()函數,會報錯:

a=1
print(a.is_integer())

#報錯
Traceback (most recent call last):
? File "E:/PycharmOut/Test/TestAll/testString/intOrFloat.py", line 7, in <module>
? ? print(a.is_integer())
AttributeError: 'int' object has no attribute 'is_integer'

嚴格的檢查方法

思路是:先檢查輸入的內容是否可以轉成float,之后再判定有沒有帶小數點

def isIntSeriously(number):
? ? result = False
? ? try:
? ? ? ? n = float(number)
? ? ? ? if n.is_integer() and str(number).count('.') == 0:
? ? ? ? ? ? result =True
? ? except :
? ? ? ? print('非數字')

? ? return result


print(isIntSeriously('a3'))
print()
print(isIntSeriously('3'))
print()
print(isIntSeriously('3.0'))

#結果
非數字
False

True

False

小結:

當輸入確定為浮點類型時,我們關心的數值是否為整數,可以使用is_integer(),

比如我就希望1.0,2.0這樣的是整數

當不確定輸入類型時,可以使用上述嚴格的判定方法

判斷輸入的字符串是否是整數還是小數

遇到一個問題:如果輸入的是字符串還是整數或者是小數如何將他們區分?

首先isdigit()只能用來判斷字符串輸入的是否是整數,無法判斷是否是小數

所以,先判斷該字符串是否是整數,如果是返回3,

不是的話說明是字母或者是小數,然后判斷是否是小數,如果是小數的話返回1,

是字母的或其他的話返回2

def is_float(i):
? ? if i.isdigit():#只能用來判斷整數的字符串
? ? ? ? return ?3
? ? else:
? ? ? ? if i.count('.') == 1: ?# 先判斷里面有沒有小數點
? ? ? ? ? ? new_i = i.split('.') ?# 去掉小數點
? ? ? ? ? ? right = new_i[-1] ?# 將小數分為小數點右邊
? ? ? ? ? ? left = new_i[0] ?# 小數點左邊
? ? ? ? ? ? if right.isdigit(): ?# 如果小數點右邊是數字判斷小數點左邊
? ? ? ? ? ? ? ? if left.isdigit(): ?# 如果小數點左邊沒有-直接返回
? ? ? ? ? ? ? ? ? ? return 1
? ? ? ? ? ? ? ? elif left.count('-') == 1 and left.startswith('-'): ?# 如果小數點左邊有-
? ? ? ? ? ? ? ? ? ? new_left = left.split('-')[-1] ?# 判斷去掉后的還是不是數字
? ? ? ? ? ? ? ? ? ? if new_left.isdigit(): ?# 是數字則返回True
? ? ? ? ? ? ? ? ? ? ? ? return 1
? ? ? ? else:
? ? ? ? ? ? return 2 ?# 返回2說明是字母

輸入例子:1.2,-1.2,.2,-2.

def is_float(i):
? ? if i.count('.') == 1:#先判斷里面有沒有小數點
? ? ? ? ? ? new_i = i.split('.')#去掉小數點
? ? ? ? ? ? right = new_i[-1]#將小數分為小數點右邊
? ? ? ? ? ? left = new_i[0]#小數點左邊
? ? ? ? ? ? if right.isdigit():#如果小數點右邊是數字判斷小數點左邊
? ? ? ? ? ? ? ? if left.isdigit():#如果小數點左邊沒有-直接返回
? ? ? ? ? ? ? ? ? ? return True
? ? ? ? ? ? ? ? elif left.count('-')== 1 and left.startswith('-'):#如果小數點左邊有-
? ? ? ? ? ? ? ? ? ? new_left = left.split('-')[-1]#判斷去掉后的還是不是數字
? ? ? ? ? ? ? ? ? ? if new_left.isdigit():#是數字則返回True
? ? ? ? ? ? ? ? ? ? ? ? return True
? ? else:
? ? ? ? return False

更簡單的判斷方法:

while ?True:
? ? num = input("請輸入一個數字:")
? ? try:
? ? ? ? n1=eval(num)
? ? except:
? ? ? ? print("輸入的不是數字程序結束")
? ? ? ? break
?
? ? if isinstance(n1,float):
? ? ? ? print('輸入的是小數請重新輸入:')
? ? ? ? continue
? ? else:
? ? ? ? print("輸入的是整數沒問題")

總結

原文鏈接:https://blog.csdn.net/weixin_42670810/article/details/112619963

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新