4

I'm trying to write a Collatz sequence while adding a try and except statements to detect whether the user types in a noninteger string and I can't seem to figure out how to do so. If read Try/Except in Python: How do you properly ignore Exceptions?, but am still at a loss. My code so far:

def collatz(y):
    try:
        if y % 2 == 0:
            print(int(y/2))
            return int(y/2)

        else:
            print(int(y*3+1))
            return int(y*3 +1)

    except ValueError:  
        print('Error: Invalid Value, the program should take in integers.')

print('Please enter a number and the Collatz sequence will be printed')
x = int(input())

while x != 1:
    x = collatz(x)
Community
  • 1
  • 1
Lukasz
  • 2,476
  • 10
  • 41
  • 51
  • 1
    put your `try` block around `int(input())`, not your function – R Nar Dec 18 '15 at 19:26
  • 1
    It is better to check for appropriate input _before_ entering the collatz function. That is, put a try-except block around the part where you get input from the user. – senshin Dec 18 '15 at 19:26
  • @RNar, that's not a duplicate at all. OP here understands that exceptions are the solution to the problem, they're just used wrong. OP in the "duplicate" didn't have a clue about them. – kdbanman Dec 18 '15 at 19:46

1 Answers1

2

On non integer input, the program will fail before you call collatz() with the code as you've written it, which means your try block will not catch the exception:

def collatz(y):
    try:
        if y % 2 == 0:
            print(int(y/2))
            return int(y/2)

        else:
            print(int(y*3+1))
            return int(y*3 +1)

    except ValueError:  
        print('Error: Invalid Value, the program should take in integers.')

print('Please enter a number and the Collatz sequence will be printed')
x = int(input())  # <-- THIS throws ValueError if input is non integer...

while x != 1:
    x = collatz(x)  # <-- ...but your try/except is in here.

Instead, wrap the input conversion in the same try/except. Then it isn't necessary in the collatz() function:

def collatz(y):
    if y % 2 == 0:
        print(int(y/2))
        return int(y/2)
    else:
        print(int(y*3+1))
        return int(y*3 +1)


print('Please enter a number and the Collatz sequence will be printed')
try:
    x = int(input())
except ValueError:  
    print('Error: Invalid Value, the program should take in integers.')
    exit()

while x != 1:
    x = collatz(x)
kdbanman
  • 10,161
  • 10
  • 46
  • 78