5

I am reading Learn Python the Hard Way by Zed Shaw. In this lesson he writes: "Every if-statement must have an else."

What are the benefits of ending every if-statement with an else? Are there any legitimate reasons not to end an if-statement with an else?

user281377
  • 28,352
  • 5
  • 75
  • 130
Brian Dant
  • 153
  • 1
  • 4
  • I don't work in Python, but I suspect that may have something to do with the way indendation controls scope (as I understand it). He might be saying that you must ALWAYS have an `else` to make the end of the condition block more obvious, even if the `else` does nothing. I've never heard such a recommendation for other languages, and to say you *must* do it seems very excessive. – FrustratedWithFormsDesigner Mar 22 '12 at 20:17
  • 4
    IMO an empty `else` doesn't make any sense, and not every `if` needs to do something useful in the `else` branch. An `else` that should never be reached is suspicious in the first place, because why would I write an `if` when I'm sure that it will always be true? Maybe there a special reasons that only apply to python, though. – user281377 Mar 22 '12 at 20:18
  • 2
    @ammoQ I'm with you, and there's nothing Python-specific that comes to mind. This rule seems bullshit, although the context makes it less of an atrocity and more of a seemingly pointless rule. –  Mar 22 '12 at 20:20
  • 2
    By the way, the recommendation "Do not use a debugger", given on the same page, is questionable at best. I would take anything he writes with a grain of salt. – user281377 Mar 22 '12 at 20:21
  • 6
    The benefit is that by doing completely pointless things you are learning Python the hard way, as promised. – psr Mar 22 '12 at 20:55

4 Answers4

13

Directly under the list of rules is the following statement:

Never be a slave to the rules in real life. For training purposes you need to follow these rules to make your mind strong, but in real life sometimes these rules are just stupid. If you think a rule is stupid, try not using it.

It looks like the rules are setup to be overly cautious because the target audience is just starting. By doing this, it forces the student to form good habits when writing future code. If you are able to explain why you no longer think the rule is worth following (and support it with a good reason), you are already thinking deeply on the issue. This means you have weighed the options and decided to accept what risk there might be. You are also less likely to make a mistake the rule would have prevented if you have spent that much time thinking about the rule.

unholysampler
  • 7,813
  • 1
  • 30
  • 38
  • 3
    Since this rule hardly ever makes sense, I see no point in teaching it to students. Or anyone else, for the matter. Writing senseless code isn't a good habit, it's either sluttery or (like in this case) superstition. – user281377 Mar 22 '12 at 20:42
  • 2
    @ammoQ: While I agree that the rule has no place in the real world and I wouldn't have put it in a book, I can see it benefiting a new student some. It causes your code to fail as soon as it does something you don't intend. This will prevent a new student from spending lots of time looking at the exception point when the error is caused by a logic error earlier in the code. It is also forcing the student to think about their if clauses. What is it checking? What is the opposite of that? Is there ambiguity in how the clause was written? – unholysampler Mar 22 '12 at 21:08
  • unholysampler: I don't get your point. Sure, there are `if`s that would better be `assert`s, so we want the code to fail. But the rule applies to each and every if, even those where evaluating the condition to `false` is perfectly valid and there is nothing to do in the `else` branch. Writing `else` *just because the rule says so* is senseless. – user281377 Mar 22 '12 at 21:26
  • @ammoQ: The book is taking the stance that is better to know everything that is going on rather than letting examples just work. When you are just starting as a programmer, getting verification that thing you intend to __not__ happen did __not__ happen can help you debug code. Again, I don't support the rule or the author claim that print statements are the only way to debug code, but I can see where he is coming from given the initial mission statement. – unholysampler Mar 22 '12 at 21:47
  • 1
    @unholysampler: I misread the book's Warning that you posted in your answer! I read "sometimes **the** rules are stupid," instead of "**these** rules are stupid." That changes *everything*. Thanks for being more attentive than me. *Sheepishly leaves room.* – Brian Dant Mar 22 '12 at 22:41
  • @unholysampler: Again, I'm not talking about `else` branches used to catch unexpected conditions. My concern is about *empty* `else` branches, as in `if result>10000: salary+=bonus else /*sorry no bonus*/` – user281377 Mar 23 '12 at 09:29
3

I have worked with code that has a case that "absolutely won't happen". And then it happens... Even if the else clause logs the problem it makes sure that you'll find it when it bites you later on.

I don't know much about code coverage, but I would think you would get better results if all paths are covered.

Paul
  • 730
  • 3
  • 13
  • 2
    If the `else` cannot happen (= the conidition must always be true), what's the point in having a branch? Just drop the `if`, and `assert condition` to get the same sanity check without confusing readers. –  Mar 22 '12 at 20:19
  • What does code coverage have to do with this? It's not about unit testing. – Michael K Mar 22 '12 at 20:19
  • 1
    @delnan - "logical" can never happen is different from "business" can never happen. There is a lot of - that never happens - assumptions living in code! – Martin Beckett Mar 22 '12 at 20:24
  • 1
    @MartinBeckett Yeah, but these are better handled with an assertion or something, not by a pointless `if`. There are numerous ways to get that security - `if must_always_be_true { half_of_method() } else { cannot_happen(); }` is one way to do it, but as others have argued, you should do [early `return`/`throw`](http://programmers.stackexchange.com/q/18454/7043) instead. I'd go as far as claiming it's the only sensible variant (most of StackExchange seems to agree) - if you need a dozen `if`s to get to the actual code, you got way too much (pointless too!) indentation. –  Mar 22 '12 at 20:31
1

I think it depends on what your purpose is. If you want for example to error check a function you dont need an else-statement:

    def foo(bar):
        if(bar<0 or bar>10) or not isinstance(bar,int):
            return -1
        print "successfull"
        print bar

But if you something more complex like if that... do this this this... and else... do this this this... then you should do "else" for readability, even if it is not really necessary.

1

I think he's trying to demonstrate something about flow control. What exactly he's trying to demonstrate is anyone's guess, but I think he's trying to make you stop and think about what the "path not taken" in any if-statement would do. Presumably he's run into a problem in the past where this type of thinking would have proven useful.

This type of rule is just way to absurd to apply in real life though.

tylerl
  • 4,850
  • 21
  • 32