-2

Trying to write the Collatz Sequence program with the guidelines of "Automate the boring stuff with python" and I'm trying to figure out if there's a way to write it without having to define a global variable.

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2

    elif number % 2 == 1:
        print(3 * number + 1)
        return 3 * number + 1

while number != 1:
   collatz(int(input()))

I'm trying to follow his tip from a few pages back as to trying to limit the usage of global variables but I can't seem to find a solution to this without defining number before the function and then calling it as a global variable inside the function.

DavidG
  • 24,279
  • 14
  • 89
  • 82
Lior.M
  • 7

1 Answers1

0
def collatz(n):
    while n > 1:
        print (n)
        if n % 2 == 1:
            n = 3 * n + 1
        else:
            n = n // 2

    print (n)

Call it:

collatz(101)
An Phú
  • 457
  • 3
  • 10