2

I'm relatively new to Python, and I'm trying to make a simple Collatz calculator, which multiplies a given integer by 3 and adds one if it is odd, and divides it by two if it is even.

The issue is, the program completely breaks if any decimal, negative integer, or a zero is used. In most cases, it'll just keep spitting out numbers infinitely. I've fixed the decimal issue with the ValueError, but I still need a way to detect if a user inputs a zero or a negative number. I'd assume it'd be something like if n <= 0, but I'm not sure where I'd place that and how I should adjust the existing code.

This is what I've got so far:

print("---Dapper's Collatz Calculator---\n")
while 1 == 1:
n = input("Enter a positive integer: ")
steps= 0

try:
    int(n)
except ValueError:
    print("Input number is not a positive integer. Try another number.")
else:
    n = int(n)
    integer = n
while n != 1:
    steps += 1
    if n % 2:
        n = 3 * n + 1
    elif not n % 2:
        n = n // 2
    print(-n)
print("The integer you used ("+str(integer)+") took "+str(steps)+" steps to reach 1.\n")
input("Press Enter to try another number.")
print("\n")
print('--------------------------------------------------------------------\n\n')
  • 2
    You can search for a tutorial on validating input in Python. That should take care of your question. Do it as soon as you grab the input. Put it in a while loop that continues until you get good data (you can search for "input until valid" on Stack Overflow). – Prune Apr 12 '17 at 21:12

0 Answers0