which style is preferred?
coding-style, exception, python
Solution
Typically, exceptions carry some overhead, and are meant for truly 'exceptional' cases. In this case, this sounds like a normal part of the execution, not an 'exceptional' or 'error' state.
In general, I think your code will benefit by using the "if/else" convention, and saving exceptions for only when they are truly needed.
Problem
Option 1: ``` def f1(c): d = { "USA": "N.Y.", "China": "Shanghai" } if c in d: return d[c] return "N/A" ``` Option 2: ``` def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" } try: return d[c] except: return "N/A" ``` So that I can then call: ``` for c in ("China", "Japan"): for f in (f1, f2): print "%s => %s" % (c, f(c)) ``` The options are to either determine whether the key is in directory before hand (f1), or just fallback to the exception (f2). Which one is preferred? Why?