我刚开始学习Python,正在学习一个在线教程,但是对于下面的代码为什么不起作用有点困惑。我看过这个网站上使用if ... in
的其他例子,但它们的结构看起来都一样,所以我对if
失败的原因没有真正的理解。你知道吗
我确实注意到,虽然在教程in
中显示为紫色,但在我的笔记本中显示为绿色。。。我不确定这跟这事有没有关系。虽然它在打印输出上显示为紫色。你知道吗
提前谢谢。你知道吗
In [53]:dictVar = {}
In [54]:dictVar[25] = "Square of 5"
In [55]:dictVar["Vitthal"] = "Some dude's name"
In [56]:dictVar[3.14] = "Pi"
In [57]:dictVar.keys()
Out[57]:dict_keys([25, 'Vitthal', 3.14])
In [58]:dictVar.values()
Out[58]:dict_values(['Square of 5', "Some dude's name", 'Pi'])
In [59]:len(dictVar.keys())
Out[59]: 3
In [60]:inputKeyToDelete = input("Please enter key to delete ")
Please enter key to delete 25
In [61]:
if inputKeyToDelete in dictVar:
dictVar.pop(inputKeyToDelete)
print("OK, zapped the key-value pair for key = " + inputKeyToDelete)
In [62]:print(dictVar)
{25: 'Square of 5', 'Vitthal': "Some dude's name", 3.14: 'Pi'}
简短版本:这是因为您输入的字符串
"25"
不存在 不等于整数25
,它是字典中的一个键。你知道吗长版本:
input
返回一个字符串,类型为str
。将该字符串转换为 整数,键入int
,执行以下操作:当然,如果
inputKeyToDelete
类似于"foo"
,这将 引发异常:您可以通过捕获异常来防止这种情况:
相关问题 更多 >
编程相关推荐