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,434

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.

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
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,880