That version doesn't work. It raises KeyError on the first iteration if the if statement is false.
The point of the for / else is that the else only gets evaluated when the for terminates without a break. So in the example you only get a KeyError if the search() never returns val.
Part of the confusion I guess is that the else: in my example is paired with for, not with if, Python indentation being significant etc.
The point of the for / else is that the else only gets evaluated when the for terminates without a break. So in the example you only get a KeyError if the search() never returns val.
Part of the confusion I guess is that the else: in my example is paired with for, not with if, Python indentation being significant etc.