美文网首页
python3.6 如何判断非负整数

python3.6 如何判断非负整数

作者: LeeMin_Z | 来源:发表于2018-05-09 12:51 被阅读114次

输入是非负整数时,返回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小心:

  1. 没做压力测试
  2. 测试通过条件:随机正负小数,±0,字符串
  3. 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

相关文章

  • python3.6 如何判断非负整数

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

  • 正则表达式的使用

    非负整数:^\d+$ 正整数:^[0-9][1-9][0-9]$ 非正整数:^((-\d+)|(0+))$ 负整数...

  • 常见正则表达式

    非负整数:^\d+$ 正整数:^[0-9][1-9][0-9]$ 非正整数:^((-\d+)|(0+))$ 负整数...

  • 常用的正则表达式整理

    非负整数:^\d+$ 正整数:^[0-9][1-9][0-9]$ 非正整数:^((-\d+)|(0+))$ 负整数...

  • 633. 平方数之和 Sum of Square Numbers

    【题目描述】给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。 【示...

  • 2021-12-05 633. 平方数之和【Medium】

    给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c 。 示例 1: 示...

  • 附录

    非负整数:^\d+$ 正整数:^[0-9]*[1-9][0-9]*$ 非正整数:^((-\d+)|(0+))$ 负...

  • 633. 平方数之和

    1.题目 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c 。 示...

  • 633. 平方数之和

    给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。 示例1: 示例2...

  • 平方数之和

    题目: 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。 示例: 输入...

网友评论

      本文标题:python3.6 如何判断非负整数

      本文链接:https://www.haomeiwen.com/subject/fspnrftx.html