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.
I have added the try and except like this (with a break)
def collatz(number):
if number %2 == 0:
print(number//2)
return number//2
elif number %2 == 1:
print(3 * number + 1)
return 3 * number + 1
n = input("Give me a number: ")
while n != 1:
try:
isinstance(n, int)
n = collatz(int(n))
except:
print('Error: Invalid argument.')
break
I think that this solution may be even simpler for learners than the accepted one:
def collatzSequence(number):
if (number % 2 == 0): # if it's even
number = number // 2
else: # if it's odd
number = number * 3 + 1
print (number)
return (number)
n = int(input('Enter a number: '))
while (n != 1):
n = collatzSequence(n)
The result will something like this:
Enter a number: 5
16
8
4
2
1
def collatz(num):
if num % 2:
return 3 * num + 1
else:
return num // 2
while True:
try:
number = int(input('Enter a positive integer.'))
if number <= 0:
continue
break
except ValueError:
continue
while number != 1:
number = collatz(number)
print(number)
Every solution on this thread is missing one thing: if the user inputs "1" the function should still run the computations of the Collatz sequence. My solution:
def collatz(number):
while number == 1:
print("3 * " + str(number) + " + 1 = " + str(3*number+1))
number = 3*number+1 ##this while loop only runs once if at all b/c at end of it the value of the variable is not equal to 1
else:
while number != 1:
if number % 2 == 0:
print(str(number) + ' // 2 = ' + str(number//2))
number = number//2
else:
print("3 * " + str(number) + " + 1 = " + str(3*number+1))
number = 3*number+1
print('Please input any integer to begin the Collatz sequence.')
while True:
try:
number = int(input())
collatz(number)
break
except ValueError:
print('please enter an integer')
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input())
collatz(num)
except ValueError:
print('Please use whole numbers only.')
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.
import sys
def collatz(number):
if number % 2 == 0:
result = number // 2
print (result)
elif number % 2 == 1:
result = number * 3 + 1
print (result)
while result == 1:
sys.exit
while result != 1:
number = result
collatz(number)
print ('Enter a number')
try:
number = int(input())
collatz(number)
except ValueError:
print('Please enter a valid integer')