首页 > 解决方案 > Python - 'And' 运算符在 if 函数中无法正常使用字典

问题描述

在 Python 中使用字典时, andand运算符似乎有问题。in我有一本字典,里面列出了不同的衣服,我有一个单独的函数可以从字典中删除这些项目。

clothes = {"socks": 1, "shoes": 2}

def status():
    if "socks" and "shoes" in clothes:
        print("You are wearing socks and shoes.")
    elif "socks" in clothes:
        print("You are wearing only socks.")
    elif "shoes" in clothes:
        print("You are wearing only shoes.")
    else:
        print("You are not wearing socks or shoes.")

如果我在衣服字典中有两个socksorshoes变量,它将打印You are wearing socks and shoes.. 但是,如果我删除任何一个,它仍然可以实现第一个if功能,就好像两者都为真一样,但事实并非如此。只有当我删除两者时,我才会得到不同的输出,然后跳转到else函数。

我假设这是in操作员的问题,或者我没有正确理解and操作员的工作,但是从阅读文档来看Returns True if both statements are true,我有点不知所措。

我敢肯定还有其他方法可以解决这个问题,但我不太确定为什么它在这里不起作用。有什么线索吗?

标签: pythonpython-3.x

解决方案


在第一行中,您忘记检查“袜子”是否在衣服中。

if "socks" in clothes and "shoes" in clothes:
        print("You are wearing socks and shoes.")

推荐阅读