-1

Following along with Al Sweigarts python lessons and tried modifying his cat code some. I can input the "except ValueError" fine using just if and elif statements but I think using a while statement I am messing something up. I want this simple code to repeat when the user enters something incorrectly which is working so far. I just need to put in something that address a non integer as the input.

Is it something to do with break/continue statements not being used?

print('How many cats do you got')
numCats = int(input())

while numCats < 0:
    print('That is not a valid number')
    print('How many cats do you got')
    numCats = int(input())

if numCats >= 4:
        print('That is a lot of cats')

elif numCats < 4:
    print('That is not a lot of cats')

except ValueError:
    print('That was not a valid number')

I would just like the code to repeat if entering an invalid number while also repeating after a non-integer value. I can't get past the except ValueError part though. Thanks!

Austin
  • 25,759
  • 4
  • 25
  • 48
Mook
  • 39
  • 7
  • `except ValueError:` needs a `try` which is missing in your code posted. – Austin Dec 29 '18 at 17:18
  • @Austin it’s not at the bottom of the code? The except ValueError is showing up for me on the second to last line – Mook Dec 29 '18 at 17:20
  • @Austin maybe I misread your comment but that’s the part I’m having trouble with currently. – Mook Dec 29 '18 at 17:21
  • There should be a `try` block prior to an `except` block. – Austin Dec 29 '18 at 17:22
  • @Austin hmm it still tells me that the “except” part is invalid syntax. Should I try doing away with the while statements and just use if and elif? I thought it would be easier getting the code to repeat until a valid answer is given using the while code but maybe not haha. – Mook Dec 29 '18 at 17:27

1 Answers1

0

An except block requires a try block. It's within the try block that you find an exception and if found the except clause is run.

while True:
    try:        
        print('How many cats do you got: ')
        numCats = int(input())
        if numCats >= 0:
            break
        else:
            print('That was not a valid number')
    except ValueError:
        print('That was not a valid number')

if numCats >= 4:
    print('That is a lot of cats')

elif numCats < 4:
    print('That is not a lot of cats')
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Okay I see now! I was trying to include it at the bottom when I should’ve put it indented underneath the while statement. Thanks! – Mook Dec 29 '18 at 17:28
  • This is still not correct, if the user first enters invalid input at the first question. `ValueError: invalid literal for int() with base 10: 'three'` – handras Dec 29 '18 at 17:37