-6

I am new to Python (30 minutes). I want to know how to identify whether the number is an integer or a string, and proceed with the result using if else.

My code is:

number = input("enter the number \n")

integer = int(number)

if integer.is_integer():

    if integer > 0:
        print("positive ", integer)
    elif integer < 0:
        print("Negative ", integer)
    else:
        print("Number is", integer)
else:
    print("Enter integer value")
5
  • What exactly is the problem then? Commented Feb 20, 2017 at 7:12
  • All input will be a string. If it's not possible to cast that to an integer then integer = int(number) will fail anyway with ValueError. You can wrap it in a try/except block. Commented Feb 20, 2017 at 7:15
  • If int is able to parse the number is_integer will always return True... Commented Feb 20, 2017 at 7:16
  • It shows an error, It my bad I just add a wrong syntax. Commented Feb 20, 2017 at 7:28
  • However, This is working number = input("enter the number \n") if number.isdigit(): integer = int(number) if integer > 0: print("positive ", integer) elif integer < 0: print("Negative ", integer) else: print("Number is", integer) else: print("Enter integer value") Commented Feb 20, 2017 at 7:28

2 Answers 2

1
number = input("enter the number \n")

try:
    integer = int(number)

    if integer > 0:
        print "positive", integer
    elif integer < 0:
        print "Negative", integer
    else:
        print "Number is", integer

except ValueError:
    print("Enter integer value")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanx Bemmu, It's working :)
I try to keep except blocks as close to the cause of error as possible.
@PeterWood OK, how should I change my response?
-2

Python provides doc-typing feature which means no matter if a value defined as a String or Number. So you must only check if the value conforms numerical properties or not using isnumeric(). This method returns true if all characters in the string are numeric, false otherwise.

str = u"hello100";  
print str.isnumeric() #returns false

str = u"123900";
print str.isnumeric() #returns true

2 Comments

Except for the fact that this does not work when the input is for example "-123".
Besides, it's duck-typing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.