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
100 SEO Tips and More

100 SEO Tips and More

100 SEO Tips EVERY SEO Enthusiast Should Know. This Report 100 SEO Tips will help you to Utilize These Tips to Dominate The Search Engine Today.

Get My Free Ebook


Post a comment