我有一个空词典,我从用户输入的字母和值列表中分配键
valuesDict = {}
letters = ['S', 'u', 'v', 'a', 't']
i = 0
while i < 5:
newValue = input('Enter ' + letters[i] + ' ')
if newValue != '':
valuesDict.update({letters[i]: newValue})
i = i + 1
和一个cutdown if语句显示我的问题,该问题打印了与字典中的项目相对应的数字
if 'S' and 'v' not in valuesDict.keys():
print('1')
elif 'u' and 'v' not in valuesDict.keys():
print('2')
如果我输入u,a和t的值,则正确输出'1'
Enter S
Enter u 2
Enter v
Enter a 5
Enter t 7
1
但是,当我输入s,a和t的值时,语句" 1"的ELIF部分将输出时,当它打算为'2'
时将输出Enter S 2
Enter u
Enter v
Enter a 5
Enter t 7
1
为什么会发生这种情况,我该如何修复并避免使用?
语法if 'S' and 'v' not in valuesDict.keys()
在逻辑上不等于if 'S' not in valuesDict.keys() and 'v' not in valuesDict.keys()
。
您得到:
>>> 'S' and 'v'
'v'
仅检查v
不是S
。
您需要检查两者:
if ('S' not in valuesDict.keys()) and ('v' not in valuesDict.keys()):
示例:
>>> 'S' and 'v' not in 'xS' # equivalent to: 'v' not in 'xS'
True
>>> ('S' not in 'xS') and ('v' not in 'xS')
False