0

My son is teaching himself Python, but has stumped me with the following. Why does the Search function on this class return None?

We are obviously hitting the return as without it the function recurses indefinitely, and on the line above the value of self.found printed is correct.

class Search:
    def __init__(self):
        print("made")
        self.n = 0
        self.found = []
    def search(self, Object, List):
        if self.n == 0:
            self.found.clear()
            print("1:self.found =", self.found, "\nself.n =", self.n)
        if len(List) == self.n:
            self.n = 0
            print("2:self.found =", self.found, "\nself.n =", self.n)
            return self.found
        if List[self.n] == Object:
            self.found.append(self.n)
            print("3:self.found =", self.found, "\nself.n =", self.n)
            self.n = self.n + 1
            print("4:self.found =", self.found, "\nself.n =", self.n)
            self.search(Object, List)
        else:
            self.n = self.n + 1
            print("5:self.found =", self.found, "\nself.n =", self.n)
            self.search(Object, List)
mavnn
  • 9,101
  • 4
  • 34
  • 52
  • 4
    When you call yourself recurively, you have to return the result of the recurive call all the way up. – JohanL Jun 29 '17 at 13:52
  • 1
    If you want a function to return something, all of its possible code paths should have a `return` statement, not just one of them. This is true even for recursive functions. Related reading: https://stackoverflow.com/questions/17778372/why-does-my-function-return-none – Kevin Jun 29 '17 at 13:52
  • could you provide an example list that you are using? – Sebastian Jun 29 '17 at 13:52
  • @Kevin all branches either recurse or return, he got that far (although the layout of the function is a little... unorthodox, I'll give you) – mavnn Jun 29 '17 at 13:53
  • With recursive functions, pretend you're calling *some other function*, even when calling the same function recursively, or mentally replace the recursive call with `# and then magic happens`, to remove any confusion. *Are* you hitting the `return` statement on the first, direct call to `search`? Probably not. – deceze Jun 29 '17 at 13:53
  • 1
    @mavnn: but the recursive function calls are still *just function calls*. If you called anything other than a recursive function, would you also just ignore the value that call returned? – Martijn Pieters Jun 29 '17 at 13:56
  • @JohanL - okay, got you. Been writing in a language with implicit returns for a while and failed to spot what you meant for a moment. – mavnn Jun 29 '17 at 13:56

0 Answers0