Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function and return value
#1
def COLLATZ(NUM):
    if NUM == 1:
        return NUM
    elif (NUM%2 == 0):
        NUM = NUM/2
        print(NUM)
        COLLATZ(NUM)
    else:
        (NUM%3) == 1
        NUM = (NUM*3)+1
        print(NUM)
        COLLATZ(NUM)

print("Enter Number")
N = int(input())
NN = COLLATZ(N)
print("Enter the last Value", NN)
1. In the last iteration NUM becomes 1 and it should return NUM. Apparently it is returning None. Can someone please explain the logic behind None ?
Reply
#2
if initial value of NUM is !=1 it will enter elif or else part of the if block. there it will run recursively until NUM == 1 and then will finish initial call to COLLATZ, effectively returning None

What you should do
def COLLATZ(NUM):

    if NUM == 1:
        return NUM
    else:
        if (NUM%2 == 0):
            NUM = NUM/2
        else:
            NUM = (NUM*3)+1
        print(NUM)
        return COLLATZ(NUM)
 
print("Enter Number")
N = int(input())
NN = COLLATZ(N)
print("Enter the last Value", NN)
And please, don't use ALLCAPS for variable and function names. Per convention ALLCAPS is used for constants
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  nested function return MHGhonaim 2 613 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,283 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,183 Feb-04-2023, 12:30 PM
Last Post: caslor
  return vs. print in nested function example Mark17 4 1,744 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  How to invoke a function with return statement in list comprehension? maiya 4 2,843 Jul-17-2021, 04:30 PM
Last Post: maiya
  Function - Return multiple values tester_V 10 4,445 Jun-02-2021, 05:34 AM
Last Post: tester_V
  Get return value from a threaded function Reverend_Jim 3 17,092 Mar-12-2021, 03:44 AM
Last Post: Reverend_Jim
  Return not exiting function?? rudihammad 3 5,288 Dec-01-2020, 07:11 PM
Last Post: bowlofred
  Why does my function return None? vg100h 3 2,207 Oct-29-2020, 06:17 AM
Last Post: vg100h
  how to keep a Popen instance existant in a function return? Skaperen 7 3,151 Sep-17-2020, 07:10 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020