0

Below is the program written for hailstone sequence.

count = 0

def hailstone(n):
    """Print the terms of the 'hailstone sequence' from n to 1."""
    assert n > 0
    print(n)
    if n > 1:
        if n % 2 == 0:
            hailstone(n / 2)
        else:
            hailstone((n * 3) + 1)
    count = count + 1
    return count

hailstone(10)

After debugging this program, I see that object referenced by count that is part of global frame is not getting incremented within the function object hailstone, as per the below observation:

enter image description here

Any reason, why count does not get incremented?

overexchange
  • 15,768
  • 30
  • 152
  • 347

1 Answers1

1

The problem is that the incremented count is local to the function. The count defined in the first line of the code is in global scope

Either

  • Pass it as an argument, i.e. def hailstone(n,count) and call it as hailstone(10,count)
  • Make your count global, by having a line, global count at the starting of your function
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140