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.
def collatz(number):
if number % 2 == 0: # Even number
return number // 2
elif number % 2 == 1: # Odd number
return number * 3 + 1
print('Please enter a number') # Ask for the number
# Check if the number is an integer, if so, see if even or odd. If not, rebuke and exit
try:
number = int(input())
while number != 1:
collatz(number)
print(number)
number = collatz(number)
else:
print('You Win. The number is now 1!')
except ValueError:
print('Please enter an integer')
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.