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.
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:
while n != 1:
n = (3 * n + 1) if (n % 2) else (n // 2)
start_num = int(input('Enter a number: '))
for n in collatz_seq(start_num):
print('Error! Please try again.')
if 'y' == input('Quit (y/n)? '):