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')
\$\endgroup\$
  • \$\begingroup\$ This would be a better question if it explained what the Collatz conjecture is and how this calculates it. \$\endgroup\$ – mdfst13 Oct 4 '16 at 23:14
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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.