简体   繁体   中英

How can I add exception for when user inputs a negative number

I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

print('How many cats do you have?')
numCats = input()
try: 
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError: 
    print('You did not enter a number.')

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.

只是

raise ValueError("you must give a positive number")

Define your own exception class, which you can choose to catch or not:

class NegativeNumberException(Exception):
    pass

print('How many cats do you have?')
try:
    numCats = int(input())
    if numCats >=4:
        print('Thats a lot of cats.')
    elif numCats < 0:
        raise NegativeNumberException()
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
except NegativeNumberException as e:
    print("You entered a negative number.")
print('How many cats do you have?') try: numCats = int(input()) #Moving the int() around input() means we aren't calling int() for every if branch. #Also, need to move that in here, so it gets caught by the try/except if numCats >= 4: print('Thats a lot of cats.') elif numCats < 0: print('You need a positive amount of cats.') #just printing instead of using a raise statement, an exception is unnecessary else: print('Thats not that many cats.') except ValueError: print('You did not enter a number.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM