[英]if statement returns false, while it is true
我有 (>) 作為輸入
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:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.