我有(>)作为输入
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:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句