Home > Software engineering >  How to validate an integer with python that needs to be used in calculations
How to validate an integer with python that needs to be used in calculations

Time:11-29

I'm trying to validate that a user input int is numbers only. This has been my most recent try:

while True:

    NumCars = int(input("Enter the number of cars on the policy: "))
    NumCarsStr = str(NumCars)
    if NumCarsStr == "":
        print("Number of cars cannot be blank. Please re-enter.")
    elif NumCarsStr.isalpha == True:
        print("Number of cars must be numbers only. Please re-enter.")
    else:
        break

With this, I get the following error:

line 91, in <module>
    NumCars = int(input("Enter the number of cars on the policy: "))
ValueError: invalid literal for int() with base 10: 'g'

(I entered a "g" to test if it was working) Thanks in advance!

CodePudding user response:

Use try / except, and then break the loop if no exception is raised, otherwise capture the exception, print an error message and let the loop iterate again

while True:
    try:
        NumCars = int(input("Enter the number of cars on the policy: "))
        break
    except ValueError:
        print("You must enter an integer number")

CodePudding user response:

Thank you everyone for your suggestions! Unfortunately none of these answers did quite what I wanted to do, but they did lead me down a thought process that DID work.

 while True:

        NumCars = (input("Enter the number of cars on the policy: "))
        if NumCars == "":
            print("Number of cars cannot be blank. Please re-enter.")
        elif NumCars.isdigit() == False:
            print("Number of cars must be numbers only. Please re-enter.")
        else:
            break

After changing the NumCars input to a string, I validated with isdigit, and then when I needed the variable for the calculations, I converted it to integers at the instances where the variable would be used for calculations.

I don't know if it was the easiest or fastest way of doing this, but it worked!

CodePudding user response:

if type(input) == int: do_code_if_is_numbersonly() else: print("Numbers Only")

This checks the type of the input, and if it is integer (number) it does example code, otherwise it prints Numbers Only. This is a quick fix but in my opinion it should work well.

CodePudding user response:

You can utilize the .isnumeric() function to determine if the string represents an integer.

e.g;

    NumCarsStr = str(input("Enter the number of cars on the policy: "))
    ...
    ...
    elif not NumCarsStr.isnumeric():
        print("Number of cars must be numbers only. Please re-enter.")
  • Related