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.

The first form is preferred: It is clearer and simpler, it is more efficient (since x may be a complex expression involving some overhead to evaluate), and it is easier to maintain (again because the x is used only once rather than twice).

Python provides multiway branching using elif and else; there is no case (or switch) statement.

print "small" elif x < 100:

print "medium" elif x < 1000:

print "large" else:

print "huge"

Python 2.5 introduced a conditional expression. It is a kind of if statement that can be used in expressions, and it is equivalent to the ternary operators used by some other languages. The Python syntax is quite different from C++'s and Java's, which use ? : for their ternary operators, and it has the form trueResult if expression else falseResult; so the expression is in the middle:

print "x is zero or positive" if x >= 0 else "x is negative"

This will print "x is zero or positive" if x >= 0 evaluates to True; otherwise, it will print "x is negative".*

Python

Was this article helpful?

0 0
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment