我很想回答這個問題。
您只需要刪除兩個製表符(或8個,如果您使用空格)以使您的代碼正常工作。
減少else:
和return "Nothing"
結果的縮進:
def fetchAndReplace(dictionary, key, newValue):
keys = dictionary.keys()
for i in keys:
if i == key:
print dictionary[key]
dictionary[key] = newValue
return
else:
return "Nothing"
dictionary = {"x":1, "y":2}
print "The result is: " + str(fetchAndReplace(dictionary,"x",3))
print "The result is: " + str(fetchAndReplace(dictionary,"z",0))
這將產生:
1
The result is: None
The result is: Nothing
爲什麼?因爲通過減小壓痕,所述else
會附着for
,並且根據該documentation,所述else
部分for..else
將僅當for
循環正常退出執行(即,不break
或return
),這就是爲什麼它將迭代在所有條目中,只有當找不到密鑰時,纔會返回字符串「Nothing」。否則它將返回None
,因爲您只有語句return
。
但由於其他人已經注意到了,你可能會想是這樣的:
def fetchAndReplace(dictionary, key, newValue):
result = dictionary.get(key, "Nothing")
dictionary[key] = newValue
return result
其邏輯是保存在變量result
的dictionary[key]
原始值,如果密鑰不可用,這將是分配值Nothing
。然後,您將該密鑰的值替換爲dictionary[key] = newValue
,然後返回result
。
運行此代碼:
dictionary = {"x":1, "y":2}
print "The result is: " + fetchAndReplace(dictionary,"x",3)
print "The result is: " + fetchAndReplace(dictionary,"z",0)
會產生
The result is: 1
The result is: Nothing
你明白'for'的作用嗎? –
一旦你在'for'循環中的第一個'i'返回Nothing'',循環和函數結束。 – mVChr
'dictionary ['x'] = 6'有什麼問題? – dawg