Search code examples
pythonpython-3.xvariablesinput

Check if the input is integer float or string in python


I am a beginner in python and I am currently working on a calculator not like this: Enter Something: add "Enter 1 number : 1" "Enter 2 number : 3" The answer is 5 not like that or using eval() I Want to create a calculator where they input something like this: "add 1 3" and output should be 4. but I have to check that the first word is a string 2nd is a integer or float and 3rd is also number I have created a script but I have one problem that I don't know how to check if the input is a integer or string or float I have used isdigit() it works but it doesn't count negative numbers and float as a number I have also used isinstance() but it doesn't work and thinks that the input is a integer even when its a string and I don't know how to use the try and except method on this script

while True:
    exitcond = ["exit","close","quit"]
    operators =["add","subtract","multiply","divide"]
    uinput = str(input())
    lowereduin = uinput.lower()
    splited = lowereduin.split(" ")
    if lowereduin in exitcond:
        break
    if splited[0] == operators[0]:
        if isinstance(splited[1],int) == True:
            if isinstance(splited[2] , int) == True:
                result = int(splited[1]) + int(splited[2])
                print(result)
            else:
                print("enter a number")
        else:
            print("enter a number")

and when I run this script and type add 1 3 its says enter a number and when I only type add its give this error

Traceback (most recent call last):
  File "C:\Users\Tyagiji\Documents\Python Projects\TRyinrg differet\experiments.py", line 11, in <module>
    if isinstance(splited[1],int) == True:
IndexError: list index out of range

Can someone tell me what's this error and if this doesn't work can you tell me how to use try: method on this script.


Solution

  • You can try the following approach and play with type checking

    import operator
    
    while True:
        exitcond = ["exit","close","quit"]
        operators ={"add": operator.add,"subtract":operator.sub,"multiply": operator.mul,"divide":operator.truediv}
        uinput = str(input())
        lowereduin = uinput.lower()
        splited = lowereduin.split(" ")
        if lowereduin in exitcond or (len(splited) !=3):
            break
        try:
            if splited[0] not in operators.keys():
                raise ValueError(f"{splited[0]} not in {list(operators.keys())}")
            op = operators.get(splited[0])
            val = op(
                *map(int, splited[1:])
            )
            print(val)
        except (ValueError, ZeroDivisionError) as err:
            print(err)
            break