Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collatz Sequence. (Python 3)

Tags:

python

I've started the book "Automate The Boring Stuff" by Al Sweigart.

At the end of Chapter 3, the author suggests creating a Collatz Sequence in Python as a practice exercise. (the practice exercise suggests I use a the print function and return statement)

When I use a print() function in my code, it works great and I get all the evaluated values I want to see on the screen:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))


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


collatz(user)

Question:
How come when I want to use the return statement, the while loop only runs once?

For example, passing the integer 3 into my function with the return statement only gives me the return value of 3 and 10:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))


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


result = collatz(user)
print(result)
like image 222
R2DPoop Avatar asked Oct 19 '25 10:10

R2DPoop


1 Answers

In your code you don't re-feed the new value back into your equation. Try separating your while loop from the collatz module. I have an example of this below:

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

chosenInt = int(input('Enter an integer greater than 1: '))

print(chosenInt)

while chosenInt != 1:
    chosenInt = collatz(chosenInt)
    print(chosenInt)
like image 103
dyroyo Avatar answered Oct 20 '25 23:10

dyroyo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!