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.
Nuncjo got the solution that works. I tweaked it a little to add try and except statements for error handling.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
try:
n = input("Enter number: ")
while n > 0 and n!= 1:
n = collatz(int(n))
except ValueError:
print('whoops, type an integer, bro.')
I managed to get it right without using any return statements and nested a while loop inside the function.
number=int(input('Enter number:\n'))
def collatz(number):
while number !=1:
if number% 2 == 0:
number= number//2
print(number)
else:
number= 3 * number + 1
print(number)
collatz(number)
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
Output:
Give me a number: 3
10
5
16
8
4
2
1
Give me a number: 11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
My Code
def collatz(number):
while number != 1:
if number % 2 == 0:
print(number // 2)
number = number // 2
elif number % 2 == 1:
print(number * 3 + 1)
number = number *3 + 1
try:
print ('Enter the number to Collatz:')
collatz(int(input()))
except ValueError:
print('Enter a valid integer')
def collatz(number):
while number != 1:
if number %2==0:
number = number//2
yield number
elif number %2 ==1:
number=number*3 +1
yield number
while True:
try:
for n in collatz(int(input('Enter number:'))):
print(n)
break
except ValueError:
print('Please enter an integer')
The extra while True loop will help the program to continue functioning after the user inputs a non-integer.
Your collatz()
function should print & return only the next value. (It ends when it returns.)
The while
loop should not be inside the collatz()
function.
You've also got inconsistent variable names (n
, number
, nnumber
), and some important code is commented out.