1
\$\begingroup\$

Here is the code.

# Collatz.py - The Collatz conjecture
initiate = True
while True:
 if initiate == True:
 initiate = False
 try:
 number = float(input('Enter a number: '))
 except:
 print('Error! Please try again.')
 number = 1
 if number % 2 == 0:
 number /= 2
 elif number == 1:
 if input('Quit? (y/n)') == 'y':
 break
 else:
 initiate = True
 else:
 number *= 3
 number += 1
 print(number,end='\n----\n')
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 4, 2016 at 22:11
\$\endgroup\$
1
  • \$\begingroup\$ This would be a better question if it explained what the Collatz conjecture is and how this calculates it. \$\endgroup\$ Commented Oct 4, 2016 at 23:14

1 Answer 1

3
\$\begingroup\$

The output does not start with the number I enter, which I find a bit surprising. Rather, the output starts with the following number in the Collatz sequence.

The Collatz sequence deals with integers, so why convert the input to a float rather than an int? To catch invalid input, you should catch just ValueError rather than every kind of error. Otherwise, you wouldn't even be able to exit the program using CtrlC. Also, since you are using Python 3, you should use the // operator for integer division instead of the / operator, which does floating-point division.

The initiate flag variable is awkward. Also, the code for calculation, number input, and restarting are all mingled together. I recommend splitting the Collatz calculation code into a generator function:

def collatz_seq(n):
 yield n
 while n != 1:
 n = (3 * n + 1) if (n % 2) else (n // 2)
 yield n
while True:
 try:
 start_num = int(input('Enter a number: '))
 for n in collatz_seq(start_num):
 print(n, end='\n====\n')
 except ValueError:
 print('Error! Please try again.')
 if 'y' == input('Quit (y/n)? '):
 break
answered Oct 5, 2016 at 0:03
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.