No Dangling Else Trap

One additional benefit of using indentation is that the “dangling else ambiguity” is impossible in Python. For example, here is some C++ code:

The code sets z to 1 if both x and y are greater than 0, and it looks like it will set z to 5 if x is less than or equal to 0. But in fact, it sets z to 5 only if x is greater than 0 and if y is less than or equal to 0. Here is what it means in Python:

And if we really want z set to 5 if x is less than or equal to 0, we would write this:

Thanks to Python’s indentation-based block structure, we avoid the “dangling else” trap.

PythonVsC++ (last edited 2009-04-27 18:51:33 by 89)

Unable to edit the page? See the FrontPage for instructions.