我已经为数字的 collat​​z 模式编写了一个 python 代码,我想计算达到 1 所花费的步数。我该怎么做?

I have written a python code for the collatz pattern for number and I want to count the number of steps it took to reach 1. How can I do it?

def collatz(n):
    while n > 1:
        print(n, end=' ')
        if (n % 2):
            # n is odd
            n = 3*n + 1
        else:
            # n is even
            n = n//2
    print(1, end='')
 
 
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)

只需添加一个计数器

def collatz(n):
    counter = 0
    while n > 1:
        counter += 1
        print(n, end=' ')
        if (n % 2):
            # n is odd
            n = 3*n + 1
        else:
            # n is even
            n = n//2
    print(1, end='\n')
    print("Number of steps until convergance :" + str(counter))
 
 
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)