-9

I just tried to run and play with some def to train myself, accidently when I call this function here and there, it loops over and over until reach 3000 times.
why counting 3000 times, and stop.

def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" %(arg1, arg2)
    print_no_thing()


def print_no_thing():
    print ("No thing ")
    print_two_again("me and ", "you")

def print_two_again(arg1,arg2):
    print "arg1:%r, arg: %r" %(arg1,arg2)
    print_two("pack","packer")

print_two_again("cool", "cooler")
Rekaut
  • 1
  • 7

1 Answers1

2

Assuming the problem is that you don't want to loop, you need have what is called a terminal condition. Currently:

  • print_two_again calls print_two
  • print_two calls print_no_thing
  • print_no_thing calls print_two_again

There are no conditional clauses so the functions will continue to call each other and never stop. You need to instrument something that will cause it to quit. There are two ways of doing this:

  • Don't have your last function call your first function.
  • Keep track of how many times you're looping and eventually stop.

For the first:

def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" %(arg1, arg2)
    print_no_thing()


def print_no_thing():
    print ("No thing ")

def print_two_again(arg1,arg2):
    print "arg1:%r, arg: %r" %(arg1,arg2)
    print_two("pack","packer")

print_two_again("cool", "cooler")

For the second:

# Note that you shouldn't actually use global variables, but this is clear for demonstration purposes
max_loops = 100
current_loops = 0

def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" %(arg1, arg2)
    print_no_thing()


def print_no_thing():
    print ("No thing ")
    if max_loops > current_loops:
        current_loops += 1
        print_two_again("me and ", "you")

def print_two_again(arg1,arg2):
    print "arg1:%r, arg: %r" %(arg1,arg2)
    print_two("pack","packer")

print_two_again("cool", "cooler")

The reason it is currently stopping at three thousand is that you're hitting the maximum recursion depth for Python. Each function will create a new 'stack frame', and because you are never returning from your functions (only calling new functions), you are only ever adding new stack frames. Eventually you will run out (when you reach your maximum recursion depth). See this for more.

Note that while it's possible to play with the maximum recursion depth, it's not recommended. 3000 is far beyond what you should need for the vast majority of use cases.

Community
  • 1
  • 1
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102