Chanderkant
Chanderkant

Reputation: 11

How to handle ValueError while if int() is provided non-integer

Python reads function input() as string. Before passing it to my function for division, variables are typecasted into int using int(). If one variable is non-int (eg "a") then how to catch it?

def divideNums(x,y):
    try:
        divResult = x/y
    except ValueError:
        print ("Please provide only Integers...")
    print (str(x) + " divided by " + str(y) + " equals " + str(divResult))

def main():
    firstVal = input("Enter First Number: ")
    secondVal = input("Enter Second Number: ")
    divideNums (int(firstVal), int(secondVal))

if __name__ == "__main__":
    main()

How to handle typecast of firstVal / secondVal ?

Upvotes: 1

Views: 91

Answers (2)

user3089519
user3089519

Reputation:

You are right about using a try/except ValueError block, but in the wrong place. The try block needs to be around where the variables are converted to integers. Eg.

def main():
    firstVal = input("Enter First Number: ")
    secondVal = input("Enter Second Number: ")

    try:
        firstVal = int(firstVal)
        secondVal = int(secondVal)
    except ValueError:
        # print the error message and return early
        print("Please provide only Integers...")
        return

    divideNums (firstVal, secondVal)

Upvotes: 1

Amit Nanaware
Amit Nanaware

Reputation: 3346

You can use isdigit function to check if the input values are integer or not

def main():

    firstVal = input("Enter First Number: ")
    secondVal = input("Enter Second Number: ")
    if firstVal.isdigit() and secondVal.isdigit():
        divideNums (int(firstVal), int(secondVal))
    else:
        print ("Please provide only Integers...")

Upvotes: 1

Related Questions