Python Forum
Why not getting return on line #16?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why not getting return on line #16?
#9
This is your code solving for n = 6, but instead of recursively calling convert() it calls a different version of convert for each value of n. So convert6() calls convert2() calls conver1() which calls convert0().
def convert0():
    return new

def convert1():
    new.append(2 % 3 - 1)
    convert0()

def convert2():
    new.append(3 % 3 - 1)
    convert1()

So while you are correct that return will jump you out of a function, it will not jump you back out of 9 levels of function calls.  It only jumps you back to the function's caller, where execution resumes with the next command.

def convert6():
    new.append(7 % 3 - 1)
    convert2()
Is it now clear why convert() is returning None? convert6() does not have a return statement, and when you call convert(6), it doesn't have a return statement either. Just because convert() returns "new" when n == 0, this does not mean that value is returned by all the other calls to convert(). That is not how function calls work. Each function call will return a value or not return a value based on the code IN THE FUNCTION. Your function convert() will return a value if the argument n == 0, otherwise it does not return a value.

So while it is true that return will jump you out of a function, it does not jump you out of 9 levels of function calls. Return jumps you back to the function's caller, and execution resumes at the next line.
Reply


Messages In This Thread
Why not getting return on line #16? - by jahuja73 - Feb-10-2021, 03:18 PM
RE: Why not getting return on line #16? - by deanhystad - Feb-11-2021, 05:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Read characters of line and return positions Gizzmo28 2 2,095 Nov-04-2020, 09:27 AM
Last Post: perfringo
  Return JSON records in single line using python 2.7 anandmn85 0 2,869 May-14-2018, 09:16 AM
Last Post: anandmn85

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020