user2334056
user2334056

Reputation: 11

Validate float data type python

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.")

Upvotes: 1

Views: 17265

Answers (3)

Dylan
Dylan

Reputation: 1

while True:
        try:
          *Your Code*
except ValueError:
        print("Please enter a number:")
        else:
        break

Upvotes: -1

abarnert
abarnert

Reputation: 365905

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.)

Upvotes: 6

user701322
user701322

Reputation: 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) 

Upvotes: -1

Related Questions