python - Why is my method returning None? -


i have following method call:

ncols = 3         npegs = 4   first_guess = []  print("calling first guess method") first_guess = firstguess(ncols, npegs, first_guess) print("after method call: " + str(first_guess)) 

firstguess method:

def firstguess(ncols, npegs, first_guess): """used setting first guess of game"""   print("in firstguess method")   c in range(1, ncols + 1):      if len(first_guess) == npegs:          print("about return first guess: " + str(first_guess))          return first_guess      else:          first_guess.append(c)    print("out of loop, first_guess len " + str(len(first_guess)) + ", " + str(first_guess))   if len(first_guess) <= npegs: #there less color options pegs      firstguess(ncols, npegs, first_guess) 

this seems returning none reason cannot figure out.

here output:

calling first guess method in firstguess method out of loop, first_guess len 3, [1, 2, 3] in firstguess method return first guess: [1, 2, 3, 1] after method call: none traceback (most recent call last): file "mastermind.py", line 323, in <module> sys.exit(main()) file "mastermind.py", line 318, in main playonce() file "mastermind.py", line 160, in playonce first_guess = first_guess + str(g[0][i]) typeerror: 'nonetype' object not subscriptable 

why returning none instead of [1, 2, 3, 1]?

the problem you're hitting recursive call doesn't return result.

so, prints "out of loop…", makes recursive call. recursive call returns something… but outer call ignores , falls off end, means none.

just add return before call firstguess:

print("out of loop, first_guess len " + str(len(first_guess)) + ", " + str(first_guess)) if len(first_guess) <= npegs: #there less color options pegs    return firstguess(ncols, npegs, first_guess) 

this still leaves path don't return (if "out of loop", , len(first_guess) > npegs)… but don't have logic useful there. may want add kind of assert or raise if believe never happen.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -