Search code examples
pythoninputuser-input

I am trying to take an input in python 2.7 and allow it to distinguish between strings and integers


I'm new and tried the search function but couldn't find an appropriate method and would appreciate any support possible.

I would like to amend this code to allow user input of a number or word. If Var a and b are numbers, the code will test for an int and compare the size of the numbers, however if a word is selected it will test for a string and print string involved. I am trying to keep the code fairly simple.

varA = raw_input('Enter a number or string ')

varB = raw_input('Enter a number or string ')

if type (varA) == str or type (varB) == str:

    print "string involved"
elif varA > varB:
    print "bigger"
elif varA == varB:
    print "equal"
elif varA < varB:
    print "smaller" 

Solution

  • You can use var.isdigit() to check if your string variable is also a number. You can then cast the other choices using int(var).

    Note, if you check to see if both are a number first, you don't need the error handling.

    See code below:

     def main():
        varA = raw_input("Enter a number or string") #this is a string by default   
        varB = raw_input("Enter a number or string")
    
        aNegDigit = False
        bNegDigit = False
        stringFlag = False #used to flag strings (e.g. -abc)
    
        if(varA[0] == "-" and varA[1:].isdigit()):
            varA = -1*int(varA[1:])
            aNegDigit = True
    
        if(varB[0] == "-" and varB[1:].isdigit()):
            varB = -1*int(varB[1:])
            bNegDigit = True
    
        if (aNegDigit or bNegDigit):
            if(not(aNegDigit)):
                if(varA.isdigit()):
                   varA = int(varA)
                else:
                    stringFlag = True
    
            if (not(bNegDigit)):
                if(varB.isdigit()):
                   varB = int(varB)
                else:
                    stringFlag = True
    
            if (stringFlag == True):
                print("String Involved")
    
            else:
                compareVarStrs(varA, varB)
    
        elif(varA.isdigit() and varB.isdigit()):
            compareVarStrs(varA, varB)
    
        else:
            print("String Involved")
    
    def compareVarStrs(varA, varB):
        if (int(varA) > int(varB)):
            print ("bigger")
    
        elif (int(varA) < int(varB)):
            print ("smaller")
    
        else:
            print ("equal")
    
    main()