Python:if语句不执行else部分

时间:2017-06-12 18:45:05

标签: python python-3.x

当我运行此代码时,它总是打印1,即使最后的customFunction有(y)。我希望它可以打印其他'版本,0。我看不出有什么不对,我希望有人可以帮助我。

def customFunction(n):
    if n == x:
        print ("1")
    else:
        print ("0")

x = str()
y = str()
n = y
customFunction(y)

1 个答案:

答案 0 :(得分:3)

因为x和y都相同。看到你刚打字 x = str()y= str(),即x和y均为<class 'str'>

两者都是空字符串。 n == x == y == ''

在python解释器中尝试这个:

>>> x = str()
>>> y = str()
>>> type(x)
<class 'str'>
>>> type(y)
<class 'str'>
>>> x==y
True
>>> print(x)
                      #nothing is printed
>>> print(y)
                      #nothing is printed

所以两者都是平等的。因此,if条件始终满足,因此始终打印1。

如果您希望执行else部分,则xy应该不同。 尝试:

>>> x = str(1)
>>> y = str(2)
>>> print(x)
1
>>> print(y)
2
>>> x==y
False

现在两者都不同,所以你的else部分会被执行。

相关问题