我有 (>)作为输入
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 语句中它是假的?
请您参考如下方法:
这是由于 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:
