I am trying to count the iterations in a function, but I can't get it right. What is wrong with the code?
Every time I call the function, the counter give me zero as a result. I want to add a pause between iteration an print the result one by one, but I couldn't fix it.
My code is below:
n = 41
def collatz(n):
count = 0
if n != 1 and n % 2 == 1 :
n = n * 3 + 1
print(n)
count += 1
collatz(n)
elif n != 1 and n % 2 == 0:
n = n / 2
print(n)
count += 1
collatz(n)
else:
print('done')
print(count)
return
collatz(n)
counthas to be a global variable or something thatcollatzreturns so that the caller can add it to a running total.print(count)should be outside too.while True:just after initialisingcountand adjusting the indentation.