2017-02-18 92 views
-1

我剛剛開始使用Python並且正在關注在線教程,但對於爲什麼下面的代碼無法正常工作,我有點困惑。我已經看過其他使用if ... in的站點上的其他示例,但它們看起來都是相同的,所以對於我來說if失敗的原因並不重要。Python如果在聲明中

我注意到,儘管在教程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'} 
+0

嘗試'if inputKeyToDelete in dic tVar.keys():'或'if int(inputKeyToDelete)in dictVar:' – bluesummers

+1

什麼是所有的輸入/輸出。爲什麼不單獨發佈您的代碼和控制檯輸出? – Edward

+0

@bluesummers:'如果inputKeyToDelete在dictVar.keys():'是毫無意義的;它只是產生不必要的按鍵視圖,但在其他方面是相同的。 'int'轉換是必要的。 – ShadowRanger

回答

0

短版:這是因爲字符串"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") 
+1

我也這麼想過,但是他在輸入字符串中輸入'eval'。這不會導致它成爲一個int嗎? –

+3

嗯,不......這是在Python 2中的真實情況,但是標記表明這個人正在使用Python 3. –

+0

@JonathonReinhart https://docs.python.org/3/library/functions.html#input – melpomene