检查python中的值是否为零或不为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28210060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:55:25  来源:igfitidea点击:

Check if value is zero or not null in python

pythonpython-3.x

提问by Jamgreen

Often I am checking if a number variable numberhas a value with if numberbut sometimes the number could be zero. So I solve this by if number or number == 0.

我经常检查一个数字变量number是否有一个值,if number但有时这个数字可能为零。所以我解决了这个问题if number or number == 0

Can I do this in a smarter way? I think it's a bit ugly to check if value is zero separately.

我能以更聪明的方式做到这一点吗?我认为单独检查 value 是否为零有点难看。

Edit

编辑

I think I could just check if the value is a number with

我想我可以检查值是否是一个数字

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

but then I will still need to check with if number and is_number(number).

但我仍然需要检查if number and is_number(number)

采纳答案by Martijn Pieters

If numbercould be Noneora number, and you wanted to include 0, filter on Noneinstead:

如果number可以是None数字,并且您想包含0,请None改为过滤:

if number is not None:

If numbercan be any number of types, test for the type; you can test for just intor a combination of types with a tuple:

如果number可以是任意数量的类型,则测试类型;您可以int使用元组测试类型或类型的组合:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

也许:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimaland Fractionobjects.

允许整数、浮点数、复数DecimalFraction对象。

回答by Amey Jadiye

Zero and None both treated as same for if block, below code should work fine.

对于 if 块,零和无都被视为相同,下面的代码应该可以正常工作。

if number or number==0:
    return True

回答by Saiteja Parsi

You can check if it can be converted to decimal. If yes, then its a number

您可以检查它是否可以转换为十进制。如果是,那么它是一个数字

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

回答by Luciano Pinheiro

The simpler way:

更简单的方法:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

会打印 1

print k or j or i or h

Will print 1

会打印 1