Search code examples
pythonexcept

ValueError Still Present with Except Statement


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')

Solution

  • 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')