1

I'm coding a simple calculator in Python for my final project and I am having trouble validating the user's entered value is a float data type. I want to make it so that if the value is a string type, it would print "Value must be an integer or decimal - Please enter a valid number", and then loop it back to asking for the user input until the user gives a valid entry. I tried, but I am getting stuck. So here is my code so far:

keepProgramRunning = True

print ("Welcome to the Calculator Application!")
good = True
while keepProgramRunning:

    print ("1: Addition")

    print ("2: Subtraction")

    print ("3: Multiplication")

    print ("4: Division")

    print ("5: Quit Application")


    choice = input("Please choose what you would like to do: ")

    if choice == "1":
        n1 = float(input ("Enter your first number: "))
        n2 = float(input ("Enter your second number: "))
        print ("Your result is: ", n1 + n2)
    elif choice == "2":
        n1 = float(input ("Enter your first number: "))
        n2 = float(input ("Enter your second number: "))
        print ("Your result is: ", n1 - n2)
    elif choice == "3":
        n1 = float(input ("Enter your first number: "))
        n2 = float(input ("Enter your second number: "))
        print ("Your result is: ", n1 * n2)
    elif choice == "4":
        n1 = float(input ("Enter your first number: "))
        n2 = float(input ("Enter your second number: "))
        try:
            print ("Your result is: ", n1 / n2)
        except:
            if n2 == 0:
                print ("Zero Division Error - Enter Valid Number")
                while good:
                    n2 = float(input ("Enter your second number: "))
                    if n2!=0:
                        good =False
                        print ("Your result is: ", n1 / n2)
    elif choice == "5":
        print ("Thank you for using the calculator. Goodbye!")
        keepProgramRunning = False
    else:
        print ("Please choose a valid option.")

3 Answers 3

6

Assuming you're using Python 3.x here, each of these lines:

n1 = float(input ("Enter your first number: "))

… will raise a ValueError if given something that can't be converted to a float.

So, instead of validating and then converting, just try to convert, and let the converter be its own validator.

For example, instead of this:

n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 + n2)

… you can do this:

while True:
    try:
        n1 = float(input ("Enter your first number: "))
        n2 = float(input ("Enter your second number: "))
    except ValueError:
        print("When I ask for a number, give me a number. Come on!")
    else:
        print ("Your result is: ", n1 + n2)
        break

If you want to check each value separately, just do two smaller loops over try instead of one big one.


Instead of copying and pasting this code 6 times, it would be better to refactor it into a function. Something like this:

def get_two_floats():
    while True:
        try:
            n1 = float(input ("Enter your first number: "))
            n2 = float(input ("Enter your second number: "))
        except ValueError:
            print("When I ask for a number, give me a number. Come on!")
        else:
            return n1, n2

Or, if you want to validate each one separately:

def get_float():
    while True:
        try:
            return float(input ("Enter your second number: "))
        except ValueError:
            print("When I ask for a number, give me a number. Come on!")

def get_two_floats();
    return get_float(), get_float()

Then you can do this:

if choice == "1":
    n1, n2 = get_two_floats()
    print ("Your result is: ", n1 + n2)
elif choice == "2":
    n1, n2 = get_two_floats()
    print ("Your result is: ", n1 - n2)
# etc.

As a side note: To catch division by zero, instead of handling all exceptions and then trying to figure out, based on the inputs, what caused the error, just handle ZeroDivisionError. (In general, a bare except: is a bad idea unless you're going to be using sys.exc_info(), re-raise-ing, or something similar. Using except SpecificException: is almost always better. Or, more often, except SpecificException as e:, so you can do something with e, like print it out in the error message.)

Sign up to request clarification or add additional context in comments.

Comments

-1
# get original input
n1 = raw_input("enter your number: ")

while not (n1.isdigit()):
# check of n1 is a digit, if not get valid entry
    n1 = raw_input ("enter a valid number: ")

num1 = float(n1) # convert string to float



n2 = raw_input("enter number: ")
while not (n2.isdigit()):
    n2 = raw_input("enter a valid number: ")

num2 = float(n2) 

1 Comment

This is (a) a bad idea, (b) not correct ("3.2" is a perfectly valid float, but it's not going to pass isdigit()), (c) for the wrong version of Python (the OP was almost certainly using Python 3.x, given his use of print as a function, input as something that returns a string, etc.), and (d) not standard Python style (e.g., adding extra parens around the while conditions).
-1
while True:
        try:
          *Your Code*
except ValueError:
        print("Please enter a number:")
        else:
        break

1 Comment

Hi and welcome to SO. It's great you start here by helping other. However, how does your code answers the question? Can you please provide some explanations to your code and why do you think it help in number validation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.