简体   繁体   中英

Error handling in python for custom exceptions

I am trying to put an error exception on these operators. Basically i want to throw an error if anything other than the items on the list is inputted. I know why this code is not working but i am not sure how to fix it. Please help me make this work. Thank you

while True:
        sign = ["+", "-" , "/" , "*"]
        try:
            operation_type=(input("what operation type you want to do?"))
            for i in range (len(sign)) :
                
                if (operation_type!= sign[i]):
                    print ("pass")
                    raise Invalid
                    i+=1
                break
        except Invalid:
            print("Please input + or - or / or *")

Here is what I found that worked best (I have included comments which should explain everything):

sign = ["+", "-" , "/" , "*"]

while True:
    operation_type=input("what operation type you want to do?")

    if operation_type in sign:#If the input is in one of the operations in sign, then quit.
        print(operation_type, 'passed')
        break#Break out of checking loop, as the requirement is met

    print('that is not the required operation')#Essentially your exception
         
 print('program done')

I hope this is what you are looking for!

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