0

I wrote a program to do the collatz sequence in python 3. This was what I was asked to do:

Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.

Remember to convert the return value from input() to an integer with the int() function - otherwise, it will be a string value.

Here's my code:

def collatz(number):
    while number is not 1:

        if number % 2 == 0:
            number = number // 2
            print(number)

        else: 
            number = 3 * number + 1
            print(number)

p = int(input("Please input an integer: "))
print(p)
collatz(p)

I know I haven't added input validation, however apart from that could I get some feedback on this code? It works as intended.

I also saw this post and I don't get why they added the return statement after the print statement.

Seanny123
  • 8,776
  • 13
  • 68
  • 124
  • 1
    Possible duplicate of [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) – Nathan Hughes Aug 31 '18 at 13:18

2 Answers2

0

if you just want to "see" your number, print() is sufficient. However, if you actually want to take the result your function is producing, you need to return number to use it outside of the function. that way, you could put return number behind your calculations in if and else and then after you call the function, you can do

nb_to_print = collatz(p)
print(nb_to_print)

That way, as stated, you can access the return value of the function outside of it too!

Also you don't need to print(p) since the inputted number is seen in the input()-statement already.

Cut7er
  • 1,209
  • 9
  • 24
0

It is true that when you return from a function you can see the result of your function the same as when you print. But your computer “program” cannot see that result only if you print. A print is meant for your eyes, a return is meant for your computer.

To give your more context, when a program runs, it is allocated some space in the memory. All the variables for your function live in that memory. When a function runs, it uses that memory to declare variables and when the function finishes those variables are deallocated and so is that memory space.

To have access to a variable in that memory space AFTER the function is done, you need to use return. print will put that variable in another part of the memory that, in summary and ultimately, will be used to show it on the monitor and won’t easily be accessible to your program for subsequent uses.

So you could gather that, depending on the use case, you might want to use only print, only return or both.

maininformer
  • 967
  • 2
  • 17
  • 31