1

First post, feedback appreciated!

I am new to python and currently working my way through 'Automate the Boring Stuff' when I stumpled upon an exercise about error-handling. In the exercise I have to account for people not typing a int value in the response to the input(), which is where the try: --> except: comes in handy. BUT, what if I wanted to print a message when a negativ int value is inserted?

My code below prints the except line.

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

try:
    if int(numCats) >= 4:
        print('That is a lot of cats')
    elif numCats < 0:
        print('Did you give cats away you did not own?')
    else:
        print('That is not taht many cats')
except:
    print('You did not enter a number.')
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 3
    You forgot to convert the input to a number. `numCats < 0` should be `int(numCats) < 0`. – Aran-Fey Oct 07 '18 at 21:37
  • Thank you @Aran-Fey! Always those _little_ buggers that gets me! – Oliver Djursing Oct 07 '18 at 21:40
  • 2
    [ask user for input until valid](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) - its imho better to convert to int once and then check - not to convert every time on each if condition. – Patrick Artner Oct 07 '18 at 21:47
  • Just implemented what you shared, worked like a charm. Thank you @PatrickArtner! – Oliver Djursing Oct 07 '18 at 22:07
  • 1
    Don’t use bare `except:`; it catches special exceptions that you shouldn’t suppress. Make `try` blocks as small as possible (here, `try: numCats=int(numCats)` is enough), putting any other code that depends on it in an `else` block. And for debugging, just don’t catch anything so you get the full error and traceback. – Davis Herring Oct 07 '18 at 22:35

0 Answers0