pythonprocess-control

Process Control Issue


Why doesn't the loop end the first time collatz() returns 1?

def collatz():
    global number
    if number % 2 == 0:
        number = number // 2
        print(number)
        return number
    else:
        number = 3 * number + 1
        print(number)
        return number

try:
    number = int(input('Please enter an integer except zero.\n'))
except ValueError:
    print("ValueError: invalid value.")
    number = int(input('You must enter an integer except zero.\n'))


while collatz() != 1:   # if input(4), the output will be: 4 2 1 4 2 1 
    collatz()


# another way, which works:
while number != 1:  --> # also input(4), the output will be: 4 2 1
    collatz()

Solution

  • In your first method, you call collatz() twice in each loop:

    So, when you input 4, your output is:

    You could also write your loop like:

    while collatz() != 1:
        pass  # do nothing
    

    A bit of advice:

    You could modify it like this, for example:

    def collatz(n):
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * number + 1
        return n
    
    try:
        number = int(input('Please enter an integer except zero.\n'))
    except ValueError:
        print("ValueError: invalid value.")
        number = int(input('You must enter an integer except zero.\n'))
    
    
    while True:  # infinite loop
        number = collatz(number)
        print(number)
        if number == 1:
            # we break out of the loop
            break