4

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)
R2DPoop
  • 51
  • 1
  • 1
  • 6

2 Answers2

3

return exits the function and, therefore terminates your while loop.

Perhaps you meant to use yield instead:

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
            yield(n)
        else:
            n = n * 3 + 1
            yield(n)

print(list(collatz(user)))

Output:

This is The Collatz Sequence
Enter a number: 3
3
[10, 5, 16, 8, 4, 2, 1]

Yield is logically similar to a return but the function is not terminated until a defined return or the end of the function is reached. When the yield statement is executed, the generator function is suspended and the value of the yield expression is returned to the caller. Once the caller finishes (and assumably uses the value that was sent) execution returns to the generator function right after the yield statement.

Community
  • 1
  • 1
dawg
  • 98,345
  • 23
  • 131
  • 206
2

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)
dyroyo
  • 21
  • 2