小编The*_*oro的帖子

Python - 如果不是0.0的语句

我有一个关于if not声明的问题Python 2.7.

我写了一些代码和使用过的if not语句.在我编写的代码的一部分中,我引用了一个函数,其中包含一个if not语句来确定是否已输入可选关键字.

它工作正常,除非0.0是关键字的值.我理解这是因为0其中一个被认为是'不'.我的代码可能太长而无法发布,但这是一个类似的(尽管是简化的)示例:

def square(x=None):
    if not x:
        print "you have not entered x"
    else:
        y=x**2
        return y

list=[1, 3, 0 ,9]
output=[]


for item in list:
    y=square(item)
    output.append(y)

print output
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,我留下了:

you have not entered x
[1, 9, None, 81]    
Run Code Online (Sandbox Code Playgroud)

在哪里我想得到:

[1, 9, 0, 81]
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我可以使用列表推导,但假设我想使用该函数并获得所需的输出,我该怎么做?

我有一个想法是:

def square(x=None):
    if not x and not str(x).isdigit():
        print "you have not entered x"
    else:
        y=x**2 …
Run Code Online (Sandbox Code Playgroud)

python if-statement control-structure python-2.7

19
推荐指数
2
解决办法
4559
查看次数