Python program to call function collatz() to return number//2 or 3*number+1 until it returns 1
Problem Definition:
Develop a python program to create a function called collatz() which reads as a parameter named number.
If the number is even it should print and return number//2 and if the number is odd then it should print and return 3*number+1.
The function should keep calling on that number until the function returns a value of 1.
Video Tutorial
Source Code to Python program to call function collatz() until it returns 1
def collatz(num): if ( num == 1): return elif (num % 2 == 0): print (num) return (collatz(num//2)) else: print (num) return (collatz(3*num+1)) num = int (input("Enter the number: ")) collatz(num)
Output
Case 1:
Enter the number: 5
5
16
8
4
2
Case 2:
Enter the number: 6
6
3
10
5
16
8
4
2
Summary:
This tutorial discusses how to write a Python program to call the method named collatz() to return number//2 or 3*number+1 until it returns 1. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and the YouTube channel for video tutorials.