我试图理解为什么我编写的这段代码即使显示为假也总是显示为真?
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]
for i in word.lower():
if (i != checkList[0]) or (i != checkList[1]) or (i != checkList[2]) or (i != checkList[3]) or (i != checkList[4]):
print("true")
else:
continue
答案 0 :(得分:2)
使用and
代替or
可以,但是更好的方法是:
for i in word.lower():
if i not in checkList:
print("true")
else:
continue
或者最好是:
print('\n'.join(['true' for i in word.lower() if i not in checkList]))
或者,如果python3(注意:有点效率低下,因为我使用列表理解作为副作用。 ):
print(*['true' for i in word.lower() if i not in checkList],sep='\n')
但是,如果是python 2,则放from __future__ import print_function
或最短的
[print('true') for i in word.lower() if i not in checkList]
在所有示例中,checkList
的注释可以是:
'aeiou'
答案 1 :(得分:1)
在 Python 中,or
条件以一种特殊的方式工作,如果第一个条件为true,则不会检查其他条件,但是如果条件为false
,它将除非找到条件true
,否则请检查所有其他条件。您可以这样做:
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]
for i in word.lower():
if i in checkList:
print("true")
else:
continue
答案 2 :(得分:1)
您需要使用and
而不是or
,此外,还有更好的计数字符的方法。例如,您可以使用map
word = "the sky is blue"
chars = 'aeiou'
print(*map(lambda x : "{}:{}".format(x, word.lower().count(x)), chars))
# output,
a:0 e:2 i:1 o:0 u:1
答案 3 :(得分:0)
任何字符串都不可能一次等于所有这些不同的字母,因此它必然总是与大多数字母不相等。您的or
应该是and
,以解决此问题,因为您关心的是它不等于其中的任何,而不是不等于所有< / strong>。
答案 4 :(得分:0)
在该部分
if (i != checkList[0])
“天空中的蓝色”与“ a”不同,因此您的情况每次都是真实的
答案 5 :(得分:0)
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]
print [x not in checkList for x in word]
Result:[True, True, False, True, True, True, True, True, False, True, True, True, True, False, False]