Python如果在州里

2024-10-01 09:36:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习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'}

Tags: ofkeynameinifpisomekeys
1条回答
网友
1楼 · 发布于 2024-10-01 09:36:29

简短版本:这是因为您输入的字符串"25"不存在 不等于整数25,它是字典中的一个键。你知道吗

长版本:

input返回一个字符串,类型为str。将该字符串转换为 整数,键入int,执行以下操作:

intkey = int(inputKeyToDelete)

当然,如果inputKeyToDelete类似于"foo",这将 引发异常:

>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

您可以通过捕获异常来防止这种情况:

try:
    x = int(s)
except ValueError:
    print("That's not a number")

相关问题 更多 >