如果语句返回false,则为true

时间:2019-11-30 20:33:17

标签: python python-3.x if-statement python-requests

我有 (>)作为输入

color = ['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
nickcolor = input()
>red
nickcolor in color
>True

然后我写

if nickcolor in color == True:
    print('You are now logged in ' + nickname + ' !\n Write something in chat!')
else:
    print('Error occured. Please restart.')
>Error occured. Please restart.

为什么在if语句中为假?

1 个答案:

答案 0 :(得分:5)

这是由于Python的运算符链接逻辑:

nickcolor in color == True

实际上被解析为

(nickcolor in color) and (color == True)

color不等于True,因此整个条件为False

在这种情况下,这是偶然的,但是此逻辑通常用于算术比较,在其中很方便:

0 < x < 10

代替

0 < x and x < 10

请注意,这里实际上并不需要这些,因为nickcolor in color已经是一个条件,因此您可以这样编写if

if nickcolor in color: