如何在python中正确使用“or”命令

2024-07-05 14:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,此代码不起作用。它与“and”命令一起工作,但我不完全确定如何使用“or”。我的当前代码:

if (response1 not in symbols or letters):
    print("You did something wrong")

Tags: orand代码in命令youifnot
2条回答

Python中的or(以及大多数编程语言)与口语中的“or”不同。 当你说

if (response1 not in symbols or letters)

Python实际上将其解释为

if ((response1 not in symbols) or (letters))

这不是你想要的。所以你应该做的是:

if ((response1 not in symbols) and (response1 not in letters))

or是一个逻辑运算符。如果or之前的部分为真ish,则返回该值,如果不是,则返回第二部分。

所以在这里,要么response1 not in symbols是真的,然后返回,要么letters返回。如果letters中有东西,那么它本身就是真的,并且if语句将认为它是真的。

你在找

if (response1 not in symbols) and (response1 not in letters):
    print("You did something wrong")

相关问题 更多 >