python判断是不是整数

您所在的位置:网站首页 派是不是非负整数 python判断是不是整数

python判断是不是整数

2024-06-17 02:22| 来源: 网络整理| 查看: 265

输入是非负整数时,返回True,否则为False。暂时没找到更简单的写法,所以自己写了个函数。

# use python 3.6

def is_positive_integer(z):

try:

z_handle = int(z)

if isinstance(z_handle,int) and z_handle >= 0:

return True

else: return False

except:

return False

# should test the True/False output

while True:

i = input('please input a positive integer number: ')

print(is_positive_integer(i))

caution小心:

没做压力测试

测试通过条件:随机正负小数,±0,字符串

while 没检测退出机制

2018.5.9 V1.0

之前写的代码有点问题,输入负数时返回None。反省测试应该直观,不要绕弯。

# use python 3.6

def is_positive_integer(z):

try:

z_handle = int(z)

if isinstance(z_handle,int) and z_handle >= 0:

return True

except:

return False

# tested with while loop, no exit

while True:

i = input('please input a positive integer number: ')

if is_positive_integer(i): print(int(i))

2018.5.10 V2.0



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3