python – Making a collatz program automate the boring stuff
python – Making a collatz program automate the boring stuff
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
Heres what I came up with:
import sys
def collatz(number):
if number % 2 == 0: # Even number
result = number // 2
elif number % 2 == 1: # Odd number
result = 3 * number + 1
while result == 1: # It would not print the number 1 without this loop
print(result)
sys.exit() # So 1 is not printed forever.
while result != 1: # Goes through this loop until the condition in the previous one is True.
print(result)
number = result # This makes it so collatz() is called with the number it has previously evaluated down to.
return collatz(number)
print(Enter a number: ) # Program starts here!
try:
number = int(input()) # ERROR! if a text string or float is input.
collatz(number)
except ValueError:
print(You must enter an integer type.)
# Fully working!
python – Making a collatz program automate the boring stuff
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.
Youve also got inconsistent variable names (n
, number
, nnumber
), and some important code is commented out.