Umar ali arshad
Umar ali arshad

Reputation: 3

Differentiate between "String" and "Integer"

I am new to python and using Atom text editor/IDE. I am writing a simple code which takes input from user and tell whether it is Integer or not.Here is the code.

def check(string):
    if type(string) == int:
        return "Integer"
    else:
        return "String"

string=input()
print (check(string))

This functions returns "String" no matter what is typed i.e. 10 or hello. Please help, what changes code needs, so it could differentiate between Integer and String.

Upvotes: 0

Views: 325

Answers (3)

AmirHmZ
AmirHmZ

Reputation: 556

Try this :

def check(inp):
    if isinstance(inp , int) :
        return "Integer"
    elif isinstance(inp , str) :
        return "String"
    else:
        return "Other"

You should try using isinstance() for runtime type checking. Anyway input() always returns string.

Upvotes: 0

Victor
Victor

Reputation: 2909

Cast it and if it fails, it's a non integer

def check(string):
    try:
        int(string)
        return 'Integer'
    except ValueError:
        return 'String'

string=input('Enter anything: ')

print(string, 'is', check(string))

If you're more of an LBYL person:

def check(string):
    if string.isnumeric() or (string and string[0] in ['-', '+'] and string[1:].isnumeric()):
        return 'Integer'
    else:
        return 'String'

Upvotes: 1

Sri
Sri

Reputation: 2328

Here is a solution using isnumeric

def check(string):
    if string.isnumeric():
        return "Integer"
    else:
        return "String"

string=input()
print (check(string))

Upvotes: 0

Related Questions