I'm trying to write a collatz program using the guidelines from a project found at the end of chapter 3 of Automate the Boring Stuff with Python. I'm using python 3.4.0. Here's the project outline:
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.
The output of this program could look something like this: Enter number: 3 10 5 16 8 4 2 1
I am trying to make a function that uses if and elif statements within a while loop. I want the number to print, and then return to the beginning of the loop and reduce itself to one using the collatz sequence, with each instance of a resulting number being printed as it goes through the loop. With my current code, I'm only able to print the first instance of the number, and that number does not go through the loop after that. Here's my code:
#collatz
print("enter a number:")
try:
number = (int(input()))
except ValueError:
print("Please enter a valid INTEGER.")
def collatz(number):
while number != 1:
if number % 2==0:
number = (number//2)
#print(number)
return (print(int(number)))
elif nnumber % 2==1:
number = (3*number+1)
#print(number)
return (print(int(number)))
continue
collatz(number)
This is what I came up with on my own and based solely on what I've learned from the book so far. It took me a little bit but one of the tools I used that was invaluable to me finding my solution and has also been invaluable in learning this content is the python visualizer tool at: http://www.pythontutor.com/visualize.html#mode=edit
I was able to see what my code was doing and where it was getting hung up and I was able to continually make tweaks until I got it right.
Your
collatz()
function should print & return only the next value. (It ends when it returns.)The
while
loop should not be inside thecollatz()
function.You've also got inconsistent variable names (
n
,number
,nnumber
), and some important code is commented out.This is what I came up with for this practice exercise. It asks for an input Validates whether it's an integer. If not it rebukes and exits. If it is, it loops through the collatz sequence until the result is 1 and then you win.
I added input validation
Here's what I came up with: