简体   繁体   中英

python Calculator: Checking input validity

my code seems to work fine except it is not printing the except Exception: print("This input is invalid.") part. When I try to fix it things gets worse. Can any one help me what I am missing? Thank you!

Sample correct output:

Calculator
Give a number: hah, NEVER
This input is invalid.
Give a number: What?
This input is invalid.
Give a number: 100
Give a number: Just kidding
This input is invalid.
Give a number: 50
(1) +
(2) -
(3) *
(4) /
(5)sin(number1/number2)
(6)cos(number1/number2)
(7)Change numbers
(8)Quit
Current numbers: 100 50
Please select something (1-6): 2
The result is: 50
(1) +
(2) -
(3) *
(4) /
(5)sin(number1/number2)
(6)cos(number1/number2)
(7)Change numbers
(8)Quit
Current numbers: 100 50
Please select something (1-6): 8
Thank you!

my code:

def getnumber():
    while True:
        try:
            number = input("Give a number: ")
            if number.isdigit():
                return number

        except Exception:
            print("This input is invalid.")

def main():
    import math
    print("Calculator")
    promptForNumbers = True

    while True:

        if promptForNumbers:


            number1 = int(getnumber())

            number2 = int(getnumber())

            promptForNumbers = False
        print("(1) +\n\n(2) -\n\n(3) *\n\n(4) /\n\n(5)sin(number1/number2)\n\n(6)cos(number1/number2)\n\n(7)Change numbers\n\n(8)Quit\n")
        print("Current numbers: %s %s" % (number1, number2))
        selection = int(input("Please select something (1-8): "))        


        if selection == 1:
            print("The result is: %s" % (number1 + number2))
            print("\n")
        elif selection == 2:
            print("The result is: %s" % (number1-number2))
            print("\n")
        elif selection==3:
            print("The result is: %s" % (number1*number2))
            print("\n")
        elif selection==4:
            print("The result is: %s" % (number1/number2))
            print("\n")
        elif selection==5:
            print("The result is: %s" % math.sin(number1/number2))
            print("\n")
        elif selection==6:
            print("The result is: %s" % math.cos(number1/number2))
            print("\n")
        elif selection==8:
            print("Thank you!")
            break
        elif selection==7:
            promptForNumbers = True
        else:
            print("Selection was not correct.")  
if __name__ == "__main__":
    main()

The reason why you are not seeing your exception statement executed, is that no code within your try block will raise an exception. The constructor to int will however, raise a ValueError exception if it is passed something that isn't a number.

Based on my understanding, attempting to convert, then catching the exception is the most pythonic way to validate input in this situation. You can read more about exceptions in Python in the docs .

def getnumber():
    while True:
        try:
            return int(input("Give a number: "))
        except ValueError:
            print("This input is invalid.")

You'll want to be sure to remove the calls to int from around all calls to getnumber within main. Also, one last note. It is considered proper form to have your import statements unintended at the top of the file. If you want to learn more you can read about it at PEP8 .

Try this:

def getnumber():
    while True:
        number = raw_input("Give a number: ")

        if number.isdigit():
            return number
        else:
            print("This input is invalid.")
    if number.isdigit():
            return number

    else:

        raise ValueError('Not a valid input value.')

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