def collatz(a):
if a==1:
return a
elif a%2==0:
print(a//2)
collatz(a//2)
else:
print(a*3+1)
collatz(a*3+1)
a = int(input("Enter no. "))
print(collatz(a))
Asked
Active
Viewed 36 times
0

Moinuddin Quadri
- 46,825
- 13
- 96
- 126

Nick
- 21
- 6
-
your `elif` and `else` block aren't returning anything. you need to add return while calling `return collatz(...)` – Moinuddin Quadri Mar 21 '21 at 15:07
-
if you don't `return` your function will return `None` – Samwise Mar 21 '21 at 15:09
-
Instead of `print(collatz(a))` try just `collatz(a)` at the end – dimitris_ps Mar 21 '21 at 15:09
-
You may think about [accepting an answer](https://stackoverflow.com/help/someone-answers) to reward those how helped you, or at least comment to explain what's missing ;) – azro Mar 27 '21 at 11:44
2 Answers
1
First see Function returns None without return statement
Then your method has nothing to return, because the purpose is to see the path of values and the stop value is always 1
def collatz(a):
print(a)
if a == 1:
return # just the stop case
elif a % 2 == 0:
collatz(a // 2)
else:
collatz(a * 3 + 1)
So call it without a print, you don't expect anything to be returned
a = int(input("Enter value:"))
collatz(a)
You could even combine in
def collatz(a):
print(a)
if a % 2 == 0:
collatz(a // 2)
elif a > 1:
collatz(a * 3 + 1)

azro
- 53,056
- 7
- 34
- 70
0
You can return the functions directly:
def collatz(a):
if int(a)==1:
return a
elif a%2==0:
print(a//2)
return collatz(a//2)
else:
print(a*3+1)
return collatz(a*3+1)

berkayln
- 935
- 1
- 8
- 14