0

I am trying to create a program for that explores the collatz sequence. It works until I try to add try and except statements to ensure the user enters a number and not text. Below is the code:

def collatz(number):
    try:
        if number % 2 == 0:
            print(number // 2)
            return number // 2
        elif number % 2 == 1:
            result = 3 * number + 1
            print(result)
            return result
    except ValueError:
        print('That is not a number')

print('Enter a number')
n = int(input())

while n != 1:
    n = collatz(int(n))

I can run it with no problems if I enter numbers. However, when I enter the word "puppy" I encounter this:

Traceback (most recent call last):
  File "C:/Users/kredeker/Desktop/python/collatz2.py", line 14, in <module>
    n = int(input())
ValueError: invalid literal for int() with base 10: 'puppy'

I thought I was accounting for the ValueError with this:

except ValueError:
    print('That is not a number')
martineau
  • 119,623
  • 25
  • 170
  • 301
kredeker54
  • 15
  • 1
  • 1
    The exception handling is done in the function. `n = int(input())` is outside the function. You can drop the int call `n = input()` – Moses Koledoye Jun 21 '17 at 16:39

2 Answers2

2

You are getting the error at n = int(input())!

So try doing

try:
  n = int(input())
except ValueError:
  print('That is not a number')

The full code (so that you don't get an error with 'n'):

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        result = 3 * number + 1
        print(result)
        return result

print('Enter a number')

try:
  n = int(input())
  while n != 1:
    n = collatz(n)
except ValueError:
  print('That is not a number')
cosinepenguin
  • 1,545
  • 1
  • 12
  • 21
2

The try...except applies to only code that is run between these words, including function calls. As the traceback shows, your exception occurs on the line 14:

n = int(input())  # <---

which is caused by the string that you entered (puppy) not being interpretable as an integer in base 10.

You need to wrap this within a try ... except; but a better option would be to adopt - and adapt - the functions from this excellent answer.