Hacker News new | past | comments | ask | show | jobs | submit login

What's more, it dances very close to something that is a super-common error for novice programmers: the early return from a loop. I grade AP exams every year, and one of the hands-down most common conceptual mistakes I've seen (on problems where this is relevant) goes something like this:

    boolean lookForSomething(int parameter) {
      for (Item item: list) {
        if (item.matches(parameter))
          return true;
        else
          return false;
      }
    }
where a correct answer would omit the "else" and put the "return false;" outside the bracketed loop (or, keep a boolean variable updated and then return that after the loop is done. Let's translate that to python:

    def lookForSomething(parameter):
      for item in list:
        if matches(item, parameter):
          return true
        else:
          return false
As a conceptual matter, for a beginner who is still trying to nail down the whole notion of "can stop early when found, but have to scan the whole list if not found", it is just plain nasty that the following code is not only correct but idiomatic:

    def lookForSomething(parameter):
      for item in list:
        if matches(item, parameter):
          return true
      else:
        return false



That last one is not idiomatic (I’ll ignore the lowercase first letter of True and False).

The `else` there is superfluous; that cuts it down to this:

    def look_for_something(parameter):
        for item in list:
            if matches(item, parameter):
                return True
        return False
And then after that one should just replace the entire loop with an `any` call:

    def look_for_something(parameter):
        return any(matches(item, parameter) for item in list)
Also, if we assume a `matches()` that is simple equality, then it would just be

    def look_for_something(parameter):
        return parameter in list
… and even then, you shouldn’t have named a variable `list`.

Cut down to its essence like this, the function probably shouldn’t have even existed… ☺


Remember that I was talking about novice programmers, here. I'll concede that "idiomatic" was a bit strong (and the True/False thing was a brain fart), but I think my main point stands: encouraging the use of an "else:" that can attach to loops, with an unobvious and somewhat nuanced semantics, is not kind to newcomers. And the fact remains that the difference between a correct implementation and one that is wrong in exactly the way that a lot of newcomers get it wrong is nothing but indentation.


The 'else' after the 'if' is unnecessary, but so what? We're not running out of letters. IMO including an "else" makes it clearer.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: