I'm so tempted to answer this.
You only need to delete two tab characters (or 8, if you use spaces) in order to make your code work.
Decrease the indentation of else: and return "Nothing"
Result:
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))
This will produce:
1
The result is: None
The result is: Nothing
Why? Because by decreasing the indentation, the else will be attached to for, and according to this documentation, the else part in for..else will be executed only when the for loop exits normally (i.e., without break or return), which is why it will iterate over all entries, and only if the key is not found, it will return the string "Nothing". Otherwise it will return None, since you just have the statement return.
But as others had noticed, you would probably want something like this:
def fetchAndReplace(dictionary, key, newValue):
result = dictionary.get(key, "Nothing")
dictionary[key] = newValue
return result
which logic is to save the original value of dictionary[key] in variable result, and if the key is not available, it will be assigned the value Nothing. Then you replace the value of that key with dictionary[key] = newValue, and then return the result.
Running this code:
dictionary = {"x":1, "y":2}
print "The result is: " + fetchAndReplace(dictionary,"x",3)
print "The result is: " + fetchAndReplace(dictionary,"z",0)
will produce
The result is: 1
The result is: Nothing
fordoes?return "Nothing"on the firstiin theforloop, the loop and the function end.dictionary['x']=6?iinforis not the index; rather it is the element; means,iis actually thekeyelse:andreturn "Nothing", and it will work as you would expect. =)